├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── parmscript
├── inspectorext.cpp
├── inspectorext.h
├── jsonparm.cpp
├── jsonparm.h
├── parmbaker.lua
├── parmexpr.lua
├── parminspector.cpp
├── parminspector.h
├── parmscript.cpp
├── parmscript.h
├── pyparm.cpp
├── pyparm.h
└── xmake.lua
├── playground
├── entry.cpp
├── parms
│ └── hello.lua
└── xmake.lua
├── screenshot.png
└── tests
└── test.lua
/.gitignore:
--------------------------------------------------------------------------------
1 | tests/*.h
2 | tests/*.inl
3 | .xmake/
4 | .cache/
5 | build/
6 | vs2017/
7 | vs2019/
8 | vs2022/
9 | compile_commands.json
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "playground/imgui"]
2 | path = deps/imgui
3 | url = https://github.com/ocornut/imgui.git
4 | [submodule "playground/lua"]
5 | path = deps/lua
6 | url = https://github.com/lua/lua.git
7 | [submodule "deps/sol2"]
8 | path = deps/sol2
9 | url = https://github.com/ThePhD/sol2.git
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Parm Script
2 |
3 | With [dear ImGui](https://github.com/ocornut/imgui), it's quite easy to write one's own inspector already, but keeping the UI up-to-date with its underlaying data structure, tweaking their UI details ... still require some labor.
4 |
5 | To solve that, one approach is to use reflection information, given a structure, generate UI for each of its fields. Unreal, Unity works this way.
6 |
7 | Another approach is to define the interface first, then use that information to generate the underlying data structure - Houdini (can) work this way.
8 |
9 | I think the second approach hasn't gotten enough attention as it deserves yet, translating UI description to data structure has some great advantages:
10 |
11 | * The definition of parameter interface is not always identical to reflection information, e.g., separators/spacers/labels/groups are UI-only concepts that can make users happier, but are hard to represent in structs and metadata.
12 | * It's easier to transpile to other forms, like raw C++ structure + inspect function, or Unreal UStructs with lots of metadata but no inspector.
13 | * It's also possible to interpret the UI on the fly, without having to have a solid structure beforehand, so that end users can make their custom parameters (like in Houdini)
14 |
15 | This project was my proof of concept experiment, but it works so well that I think it already has some real world value, so I released it here.
16 |
17 | ## A taste of Parm Script
18 |
19 | // In fact, it's just Lua
20 |
21 |
22 | ```lua
23 | parmset 'Hello'
24 |
25 | label 'A Little Test:'
26 | toggle 'x' {label='Enable Group Foo', default=true}
27 | text 'name' {label='Name', default='Foo\nBar\n!@#$%^&*()_+""', multiline=true}
28 | group 'foo' {label='Foo', disablewhen='{x}==false'}
29 | label 'A Int Value:' {joinnext=true}
30 | int 'a' {max=1024, min=1}
31 | float 'b' {default=1024, ui='drag', speed=1}
32 | color 'color1' {hdr=true, default={1,0,0}}
33 | color 'yellow' {hdr=true, default={1,1,0}}
34 | color 'green' {hdr=true, default={0,1,0,1}, alpha=false, wheel=true}
35 | color 'color2' {alpha=false, hsv=true, wheel=true, default={0.3,0.1,0.4,1.0}}
36 | button 'sayhi' {label='Say Hi'}
37 | int 'c'
38 | struct 'X'
39 | float 'a'
40 | float 'b'
41 | double 'c'
42 | endstruct 'X'
43 | endgroup 'foo'
44 | spacer ''
45 | spacer ''
46 | separator ''
47 | toggle 'y'
48 | group 'bar' {closed=true, label='BarBarBar'}
49 | float2 'pos' {disablewhen='{Points}.empty()'}
50 | menu 'mode' {
51 | class='Mode', label='Mode',
52 | items={'a','b','c'}, default='b',
53 | itemlabels={'Apple','Banana','Coffe'},
54 | itemvalues={4,8,16} }
55 | color 'color3' {default={0.8,0.2,0.2,1.0}, disablewhen='{mode}!={menu:mode::a}'}
56 | endgroup 'bar'
57 | list 'Points' {class='Point'}
58 | float3 "pos" {label="Position"}
59 | float3 "N" {label="Normal", default={0,1,0}, min=-1, max=1}
60 | endlist 'Points'
61 | ```
62 |
63 | ## The look:
64 |
65 | 
66 |
67 | ## The Generator
68 |
69 | To generate code from above script, you can call parmbaker from CLI:
70 |
71 | ```
72 | $ lua parmbaker.lua tests/hello.lua
73 | ```
74 |
75 | or from Lua you can call `cppStruct()` and `imguiInspector()` function:
76 |
77 | ```lua
78 | local pe=require('parmexpr')
79 | local ps=pe(--[[the script here]])
80 | ps.setUseBuiltinTypes() -- use float[4] to represent float4, and so forth
81 | -- you can also call ps.typedef('float4', 'Vector4f') or alike if you want
82 | print('//----------CPP STRUCT-----------')
83 | print(ps.cppStruct())
84 | print('//----------IMGUI INSPECTOR----------')
85 | print(ps.imguiInspector('parms'))
86 | ```
87 |
88 | ## C++ Compiled
89 |
90 | Generated C++ structure:
91 |
92 | ```cpp
93 | struct Hello {
94 | bool x = true; // ui="toggle", label="Enable Group Foo"
95 | std::string name = "Foo\nBar\n!@#$%^&*()_+\"\""; // ui="text", multiline=true, label="Name"
96 | int a; // max=1024, min=1
97 | float b = 1024; // speed=1, ui="drag"
98 | float color1[4] = {1.0f, 0.0f, 0.0f, 1.0f}; // hdr=true
99 | float yellow[4] = {1.0f, 1.0f, 0.0f, 1.0f}; // hdr=true
100 | float green[4] = {0.0f, 1.0f, 0.0f, 1.0f}; // hdr=true, wheel=true, alpha=false
101 | float color2[4] = {0.3f, 0.1f, 0.4f, 1.0f}; // wheel=true, hsv=true, alpha=false
102 | std::function sayhi; // ui="button", label="Say Hi"
103 | int c;
104 | struct struct_X { // struct
105 | float a;
106 | float b;
107 | double c;
108 | };
109 | struct_X X; // ui="struct", label="X"
110 | bool y; // ui="toggle"
111 | float pos[2]; // disablewhen="{Points}.empty()"
112 | enum class Mode {
113 | a=4, // label=Apple
114 | b=8, // label=Banana
115 | c=16, // label=Coffe
116 | };
117 | Mode mode = Mode::b; // ui="menu", class="Mode", label="Mode"
118 | float color3[4] = {0.8f, 0.2f, 0.2f, 1.0f}; // disablewhen="{mode}!={menu:mode::a}"
119 | struct Point { // list
120 | float pos[3]; // label="Position"
121 | float N[3] = {0.0f, 1.0f, 0.0f}; // max=1, label="Normal", min=-1
122 | };
123 | std::vector Points; // ui="list", class="Point"
124 | };
125 | ```
126 |
127 | Generated ImGui inspector:
128 |
129 | ```cpp
130 | bool ImGuiInspect(Hello &parms, std::unordered_set& modified) {
131 | modified.clear();
132 | ImGui::TextUnformatted("A Little Test:");
133 | if(ImGui::Checkbox("Enable Group Foo##x", &(parms.x))) modified.insert("x");
134 | if(ImGui::InputTextMultiline("Name##name", &(parms.name)))
135 | modified.insert("name");
136 | ImGui::BeginDisabled(parms.x==false);
137 | if(ImGui::CollapsingHeader("Foo##foo", ImGuiTreeNodeFlags_DefaultOpen)) {
138 | ImGui::TextUnformatted("A Int Value:");
139 | ImGui::SameLine();
140 | if(ImGui::SliderInt("A##a", (&(parms.a)), 1, 1024))
141 | modified.insert("a");
142 | if(ImGui::DragFloat("B##b", (&(parms.b)), 1.000000f))
143 | modified.insert("b");
144 | if(ImGui::ColorEdit4("Color1##color1", (parms.color1), ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_Float))
145 | modified.insert("color1");
146 | if(ImGui::ColorEdit4("Yellow##yellow", (parms.yellow), ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_Float))
147 | modified.insert("yellow");
148 | if(ImGui::ColorEdit3("Green##green", (parms.green), ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_Float | ImGuiColorEditFlags_PickerHueWheel))
149 | modified.insert("green");
150 | if(ImGui::ColorEdit3("Color2##color2", (parms.color2), ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_PickerHueWheel))
151 | modified.insert("color2");
152 | if(ImGui::Button("Say Hi##sayhi")) {
153 | if(parms.sayhi) (parms.sayhi)();
154 | modified.insert("sayhi");
155 | }
156 | if(ImGui::DragInt("C##c", (&(parms.c)), 1.000000f))
157 | modified.insert("c");
158 | if(ImGui::TreeNodeEx("X##X", ImGuiTreeNodeFlags_Framed)) {
159 | if(ImGui::DragFloat("A##a", (&(parms.X.a)), 1.000000f))
160 | modified.insert("X.a");
161 | if(ImGui::DragFloat("B##b", (&(parms.X.b)), 1.000000f))
162 | modified.insert("X.b");
163 | if(ImGui::InputDouble("C##c", &(parms.X.c)))
164 | modified.insert("X.c");
165 | ImGui::TreePop();
166 | }
167 | }
168 | ImGui::EndDisabled();
169 | ImGui::Spacing();
170 | ImGui::Spacing();
171 | ImGui::Separator();
172 | if(ImGui::Checkbox("Y##y", &(parms.y))) modified.insert("y");
173 | if(ImGui::CollapsingHeader("BarBarBar##bar", 0)) {
174 | ImGui::BeginDisabled(parms.Points.empty());
175 | if(ImGui::DragFloat2("Pos##pos", (parms.pos), 1.000000f))
176 | modified.insert("pos");
177 | ImGui::EndDisabled();
178 | static const char* mode_labels[]={"Apple", "Banana", "Coffe"};
179 | static const Hello::Mode mode_values[]={Hello::Mode::a, Hello::Mode::b, Hello::Mode::c};
180 | int current_item_mode = 0;
181 | for(; current_item_mode < 3; ++current_item_mode)
182 | if (mode_values[current_item_mode]==(parms.mode)) break;
183 | if (ImGui::Combo("Mode##mode", ¤t_item_mode, mode_labels, 3)) {
184 | parms.mode = mode_values[current_item_mode];
185 | modified.insert("mode");
186 | }
187 | ImGui::BeginDisabled(parms.mode!=Hello::Mode::a);
188 | if(ImGui::ColorEdit4("Color3##color3", (parms.color3), ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_Uint8))
189 | modified.insert("color3");
190 | ImGui::EndDisabled();
191 | }
192 | int listPoints_cnt=static_cast((parms.Points).size());
193 | if (ImGui::InputInt("# " "Points##Points", &listPoints_cnt)) {
194 | parms.Points.resize(listPoints_cnt);
195 | modified.insert("Points");
196 | }
197 | for(int listPoints_idx=0; listPoints_idx modified;
216 | if (ImGuiInspect(parms, modified)) {
217 | ...
218 | }
219 | ```
220 |
221 | ## Runtime Interpreted API
222 |
223 | ### C++
224 |
225 | ```cpp
226 | ParmSet parms;
227 | parms.loadScript(R"$$(...)$$");
228 | parms.updateInspector();
229 | parms.dirtyEntries(); // get modified item keys between last updateInspector()
230 |
231 | parms["a"]->as() // retrieve value
232 | parms["b"]->is() // test type
233 | parms["Points[2].pos"]->as() // complex path is supported
234 | parms->get("Points")->at(2)->get("pos")->as() // equivalent of above expr
235 | ```
236 |
237 | ### Lua
238 |
239 | ```lua
240 | local ParmSet = require('ParmSet')
241 | local parms = ParmSet.new()
242 | parms:loadScript([[...]])
243 | parms:updateInspector()
244 | parms:dirtyEntries() -- get modified item keys between last updateInspector()
245 |
246 | local a = parms["a"]
247 | local b = type(parms["b"])
248 | local p = parms["Points[2].pos"]
249 | ```
250 |
251 | ## Specs
252 |
253 | ### Primitives:
254 |
255 | * `parmset 'name'` -- the name of this parm set, also the name of generated C++ struct, should be declared before anything else
256 | * `label 'text'`
257 | * `spacer()` or `spacer ''`
258 | * `separator()` or `separator ''`
259 | * `text 'name' {meta}` -- a textinput control, and the variable name, label will be `titleize(name)` by default, you can specify `label='Label'` in meta.
260 | * `int 'name' {meta}` -- a int control, you can specify `ui='drag'` or `ui='slider'` in meta, default UI is `drag`.
261 | * `float 'name' {meta}`
262 | * `float2 ...`
263 | * `float3 ...`
264 | * `float4 ...`
265 | * `double ...`
266 | * `color ...`
267 | * `toggle ...`
268 | * `menu 'name' {items={...}, itemlabels={...}}` -- defines a combo box, with items as its items. item names should be valid C++ variable name, as they will be defined as enum fields, for prettier labels, you can specify itemlabels
269 | * `struct 'name' {meta}` ... `endstruct 'name'` -- defines a struct named `struct_name` and a variable of `name`, the struct named can be changed by specify `class='StructName'` in meta, fields defined between `struct` and `endstruct` are in the struct's scope.
270 | * `group 'name' {label='Label'}` ... `endgroup 'name'` -- defines a group, but unlike `struct`, the variables in `group` are in the same scope of parent, so you can't define variable of same name even in nested groups.
271 | * `list 'name' {class='cls'}` -- defines a `std::vector` of `cls`, i.e., `std::vector name` or `std::vector name` if no `class=` meta exists. Fields defined between `list` and `endlist` are the member variables of struct `cls`
272 |
273 | ### Common Meta Info
274 |
275 | * `label` -- no need to explain
276 | * `default` -- also no need to explain
277 | * `min`, `max` -- value range for numeric types like int, float, float2, ...
278 | * `disablewhen` -- expression to mark field or group disabled, you can reference other fields with `{field}` or `{field.subfield}`, to reference class name (when comparing with menu item, which is define as `enum class` in generated code, you may need this), you can use `{menu:name::field}` to reference `field` of enum class `name`, e.g., see example [above](#example-script).
279 | * `joinnext` -- same effect as `ImGui::SameLine()`
280 | * ...
281 | * _TODO: document them all_
282 |
283 |
284 |
--------------------------------------------------------------------------------
/parmscript/inspectorext.cpp:
--------------------------------------------------------------------------------
1 | #include "parmscript.h"
2 | #include "parminspector.h"
3 | #include "inspectorext.h"
4 |
5 | #include
6 | #include
7 |
8 | #include
9 |
10 | namespace parmscript {
11 |
12 | bool inspectFilePath(Parm& parm)
13 | {
14 | string path = parm.as();
15 | auto label = "##" + parm.path();
16 | bool mod = false;
17 |
18 | auto filters = parm.getMeta("filters", "");
19 | auto dlg = NFD_OpenDialog;
20 | if (parm.getMeta("dialog", "open") == "save")
21 | dlg = NFD_SaveDialog;
22 |
23 | if (ImGui::InputText(label.c_str(), &path, ImGuiInputTextFlags_EnterReturnsTrue)) {
24 | mod = true;
25 | }
26 |
27 | ImGui::SameLine();
28 | auto btlabel = "...##" + parm.path();
29 | if (ImGui::Button(btlabel.c_str())) {
30 | char* cpath = nullptr;
31 | auto result = dlg(filters.c_str(), nullptr, &cpath);
32 | if (result == NFD_OKAY && cpath) {
33 | if (*cpath) {
34 | path = cpath;
35 | mod = true;
36 | }
37 | free(cpath);
38 | }
39 | }
40 |
41 | ImGui::SameLine();
42 | ImGui::TextUnformatted(parm.label().c_str());
43 |
44 | if (mod)
45 | parm.set(path);
46 | return mod;
47 | }
48 |
49 | bool inspectDirPath(Parm& parm)
50 | {
51 | string path = parm.as();
52 | string defaultpath = parm.getMeta("defaultpath", "");
53 | auto label = "##" + parm.path();
54 | bool mod = false;
55 |
56 | if (ImGui::InputText(label.c_str(), &path, ImGuiInputTextFlags_EnterReturnsTrue)) {
57 | mod = true;
58 | }
59 |
60 | ImGui::SameLine();
61 | auto btlabel = "...##" + parm.path();
62 | if (ImGui::Button(btlabel.c_str())) {
63 | char* cpath = nullptr;
64 | auto result = NFD_PickFolder(defaultpath.c_str(), &cpath);
65 | if (result == NFD_OKAY && cpath) {
66 | if (*cpath) {
67 | path = cpath;
68 | mod = true;
69 | }
70 | free(cpath);
71 | }
72 | }
73 |
74 | ImGui::SameLine();
75 | ImGui::TextUnformatted(parm.label().c_str());
76 |
77 | if (mod)
78 | parm.set(path);
79 | return mod;
80 | }
81 |
82 | static int keepIndentCallback(ImGuiInputTextCallbackData* data)
83 | {
84 | if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) {
85 | if (!data->HasSelection() && ImGui::IsKeyPressed(ImGuiKey_Enter)) {
86 | char const* lastnonspace = data->Buf + data->CursorPos - 1;
87 | for (; lastnonspace != data->Buf; --lastnonspace) {
88 | if (char c = *lastnonspace;
89 | c != '\n' && c != '\r' && c != '\t' && c != ' ')
90 | break;
91 | }
92 | int space = 0;
93 | char const* linestart = lastnonspace;
94 | for (; linestart > data->Buf && *linestart != '\n'; --linestart)
95 | ;
96 | if (linestart > data->Buf && *linestart == '\n')
97 | ++linestart;
98 | for (; *linestart == ' ' || *linestart == '\t'; ++linestart) {
99 | if (*linestart == ' ') space += 1;
100 | else if (*linestart == '\t') space += 4;
101 | else break;
102 | }
103 | if (data->CursorPos >= 1 && (*lastnonspace == ':' || *lastnonspace == '{'))
104 | space += 2;
105 | if (space > 0) {
106 | std::string indent = std::string(space, ' ');
107 | data->InsertChars(data->CursorPos, indent.c_str(), indent.c_str()+indent.size());
108 | }
109 | }
110 | }
111 | return 0;
112 | }
113 |
114 | bool inspectCode(Parm& parm)
115 | {
116 | auto label = parm.label() + "##" + parm.path();
117 | auto* v = parm.getPtr();
118 | // TODO: use a syntax-highlighting editor
119 | return ImGui::InputTextMultiline(label.c_str(), v, ImVec2(0,0), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackEdit, keepIndentCallback);
120 | }
121 |
122 | void addExtensions()
123 | {
124 | ParmSetInspector::setFieldInspector("file", inspectFilePath);
125 | ParmSetInspector::setFieldInspector("dir", inspectDirPath);
126 | ParmSetInspector::setFieldInspector("code", inspectCode);
127 |
128 | ParmSet::preloadScript() += "\nlocal file = alias(text, 'file')\nlocal dir = alias(text, 'dir')\nlocal code = alias(text, 'code', {font='mono', width=-16})";
129 | }
130 |
131 | } // namespace parmscript
132 |
133 |
--------------------------------------------------------------------------------
/parmscript/inspectorext.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | namespace parmscript {
3 |
4 | class Parm;
5 | class ParmSetInspector;
6 |
7 | bool inspectFilePath(Parm& parm);
8 | bool inspectDirPath(Parm& parm);
9 | bool inspectCode(Parm& parm);
10 |
11 | void addExtensions();
12 |
13 | } // namespace parmscript
14 |
--------------------------------------------------------------------------------
/parmscript/jsonparm.cpp:
--------------------------------------------------------------------------------
1 | #include "parmscript.h"
2 | #include "jsonparm.h"
3 | #include
4 | #include
5 | #include
6 |
7 | namespace parmscript {
8 |
9 | void from_json(nlohmann::json const& j, Parm& p)
10 | {
11 | if (p.ui() == Parm::ui_type_enum::FIELD) {
12 | switch (p.type()) {
13 | case Parm::value_type_enum::BOOL:
14 | p.set(j.get());
15 | break;
16 | case Parm::value_type_enum::INT:
17 | p.set(j.get());
18 | break;
19 | case Parm::value_type_enum::FLOAT:
20 | p.set(j.get());
21 | break;
22 | case Parm::value_type_enum::DOUBLE:
23 | p.set(j.get());
24 | break;
25 | case Parm::value_type_enum::STRING:
26 | p.set(j.get());
27 | break;
28 | case Parm::value_type_enum::INT2: {
29 | std::vector values = j.get>();
30 | if (values.size() != 2)
31 | throw std::runtime_error("Invalid float2 value");
32 | Parm::int2 i2 = { values[0], values[1] };
33 | p.set(i2);
34 | break;
35 | }
36 | case Parm::value_type_enum::FLOAT2: {
37 | std::vector values = j.get>();
38 | if (values.size() != 2)
39 | throw std::runtime_error("Invalid float2 value");
40 | Parm::float2 f2 = { values[0], values[1] };
41 | p.set(f2);
42 | break;
43 | }
44 | case Parm::value_type_enum::FLOAT3: {
45 | std::vector values = j.get>();
46 | if (values.size() != 3)
47 | throw std::runtime_error("Invalid float3 value");
48 | Parm::float3 f3 = { values[0], values[1], values[2] };
49 | p.set(f3);
50 | break;
51 | }
52 | case Parm::value_type_enum::FLOAT4: {
53 | std::vector values = j.get>();
54 | if (values.size() != 4)
55 | throw std::runtime_error("Invalid float4 value");
56 | Parm::float4 f4 = { values[0], values[1], values[2], values[3] };
57 | p.set(f4);
58 | break;
59 | }
60 | case Parm::value_type_enum::COLOR: {
61 | std::vector values = j.get>();
62 | if (values.size() != 4)
63 | throw std::runtime_error("Invalid color value");
64 | Parm::color c = { values[0], values[1], values[2], values[3] };
65 | p.set(c);
66 | break;
67 | }
68 | default:
69 | throw std::runtime_error("Invalid parameter type");
70 | }
71 | } else if (p.ui() == Parm::ui_type_enum::STRUCT) {
72 | if (!j.is_object())
73 | throw std::runtime_error("Invalid struct value");
74 | for (size_t numfields = p.numFields(), i = 0; i < numfields; ++i) {
75 | ParmPtr field = p.getField(i);
76 | if (!j.contains(field->name())) {
77 | // TODO: warn about missing field
78 | continue;
79 | }
80 | try {
81 | from_json(j[field->name()], *field);
82 | } catch (std::exception const& e) {
83 | continue; // skip invalid fields
84 | }
85 | }
86 | } else if (p.ui() == Parm::ui_type_enum::LIST) {
87 | if (!j.is_array())
88 | throw std::runtime_error("Invalid list value");
89 | p.resizeList(j.size());
90 | for (size_t numitems = p.numListValues(), i = 0; i < numitems; ++i) {
91 | ParmPtr item = p.at(i);
92 | try {
93 | from_json(j[i], *item);
94 | } catch (std::exception const& e) {
95 | continue; // skip invalid index
96 | }
97 | }
98 | } else if (p.ui() == Parm::ui_type_enum::MENU) {
99 | p.set(j.get());
100 | }
101 | }
102 |
103 | //////////////////////////////////////////////////////////////////////////////////////
104 |
105 | void to_json(nlohmann::json& j, Parm const& p)
106 | {
107 | if (p.ui() == Parm::ui_type_enum::FIELD) {
108 | switch (p.type()) {
109 | case Parm::value_type_enum::BOOL:
110 | j = p.as();
111 | break;
112 | case Parm::value_type_enum::INT:
113 | j = p.as();
114 | break;
115 | case Parm::value_type_enum::FLOAT:
116 | j = p.as();
117 | break;
118 | case Parm::value_type_enum::DOUBLE:
119 | j = p.as();
120 | break;
121 | case Parm::value_type_enum::STRING:
122 | j = p.as();
123 | break;
124 | case Parm::value_type_enum::INT2: {
125 | Parm::int2 i2 = p.as();
126 | j = std::array{ i2.x, i2.y };
127 | break;
128 | }
129 | case Parm::value_type_enum::FLOAT2: {
130 | Parm::float2 f2 = p.as();
131 | j = std::array{ f2.x, f2.y };
132 | break;
133 | }
134 | case Parm::value_type_enum::FLOAT3: {
135 | Parm::float3 f3 = p.as();
136 | j = std::array{ f3.x, f3.y, f3.z };
137 | break;
138 | }
139 | case Parm::value_type_enum::FLOAT4: {
140 | Parm::float4 f4 = p.as();
141 | j = std::array{ f4.x, f4.y, f4.z, f4.w };
142 | break;
143 | }
144 | case Parm::value_type_enum::COLOR: {
145 | Parm::color c = p.as();
146 | j = std::array{ c.r, c.g, c.b, c.a };
147 | break;
148 | }
149 | default:
150 | throw std::runtime_error("Invalid parameter type");
151 | }
152 | } else if (p.ui() == Parm::ui_type_enum::STRUCT) {
153 | j = nlohmann::json::object();
154 | for (size_t numfields = p.numFields(), i = 0; i < numfields; ++i) {
155 | ParmPtr field = p.getField(i);
156 | try {
157 | to_json(j[field->name()], *field);
158 | } catch (std::exception const& e) {
159 | continue;
160 | }
161 | }
162 | } else if (p.ui() == Parm::ui_type_enum::LIST) {
163 | j = nlohmann::json::array();
164 | for (size_t numitems = p.numListValues(), i = 0; i < numitems; ++i) {
165 | try {
166 | auto item = p.at(i);
167 | to_json(j.emplace_back(), *item);
168 | } catch (std::exception const& e) {
169 | continue;
170 | }
171 | }
172 | } else if (p.ui() == Parm::ui_type_enum::MENU) {
173 | j = p.as();
174 | }
175 | }
176 |
177 | //////////////////////////////////////////////////////////////////////////////////////
178 |
179 | void from_json(nlohmann::json const& j, ParmSet& p)
180 | {
181 | if (auto root = p.get(""))
182 | from_json(j, *root);
183 | }
184 |
185 | void to_json(nlohmann::json& j, ParmSet const& p)
186 | {
187 | if (auto root = p.get(""))
188 | to_json(j, *root);
189 | }
190 |
191 | } // namespace jsoncpp
192 |
193 |
--------------------------------------------------------------------------------
/parmscript/jsonparm.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | namespace parmscript {
6 |
7 | class Parm;
8 | class ParmSet;
9 |
10 | void from_json(nlohmann::json const& j, Parm& p);
11 | void from_json(nlohmann::json const& j, ParmSet& p);
12 | void to_json(nlohmann::json& j, Parm const& p);
13 | void to_json(nlohmann::json& j, ParmSet const& p);
14 |
15 | }
16 |
17 |
--------------------------------------------------------------------------------
/parmscript/parmbaker.lua:
--------------------------------------------------------------------------------
1 | local fmt=string.format
2 | local printf=function(...) print(fmt(...)) end
3 |
4 | local pe=require('parmexpr')
5 |
6 | local helpstr = [[
7 | ================
8 | PARM BAKER
9 | ================
10 |
11 | usage:
12 | lua parmbaker.lua [-H path] [-I path] [-C] [-N name] [parmscript]
13 |
14 | args:
15 |
16 | -H, --header path : output header file path
17 | -I, --impl path : output implement file path
18 | -C, --cpp : output implement as .cpp (otherwise outputs .inl)
19 | -N, --namespace name : output in namespace `name`
20 | parmscript : the parmscript input file, reads from stdin if missing
21 |
22 | ]]
23 |
24 | local input=io.stdin
25 | local headerpath, implpath
26 | local outputcpp=false
27 | local outdir='./'
28 | local skipnext=false
29 | local beginnamespace,endnamespace='',''
30 | if #arg>0 then
31 | for i=1,#arg do
32 | if skipnext then
33 | skipnext=false
34 | elseif i<#arg and (arg[i]=='-H' or arg[i]=='--header') then
35 | headerpath=arg[i+1]
36 | skipnext=true
37 | elseif i<#arg and (arg[i]=='-I' or arg[i]=='--impl') then
38 | implpath=arg[i+1]
39 | skipnext=true
40 | elseif arg[i]=='-C' or arg[i]=='--cpp' then
41 | outputcpp=true
42 | elseif arg[i]=='-N' or arg[i]=='--namespace' then
43 | local namespace=arg[i+1]
44 | skipnext=true
45 | beginnamespace=fmt('namespace %s {\n', namespace)
46 | endnamespace='}\n'
47 | elseif arg[i]=='-h' or arg[i]=='--help' then
48 | print(helpstr)
49 | os.exit(0)
50 | else
51 | input=io.open(arg[i])
52 | local namepart=arg[i]:find('[\\/][^\\/]+$')
53 | if namepart then
54 | outdir=arg[i]:sub(1,namepart)
55 | printf('default output dir is "%s"', outdir)
56 | end
57 | end
58 | end
59 | end
60 |
61 | local ps=pe(input:read('*all'))
62 |
63 | if ps then
64 | local name=ps.parmsetName()
65 |
66 | headerpath=headerpath or outdir..name:lower()..'.h'
67 | if not implpath then
68 | if outputcpp then
69 | implpath=outdir..name:lower()..'_imgui.cpp'
70 | else
71 | implpath=outdir..name:lower()..'_imgui.inl'
72 | end
73 | end
74 |
75 | printf('writing header to "%s"', headerpath)
76 | local header=io.open(headerpath, 'w')
77 | ps.setUseBuiltinTypes()
78 | header:write('//Generated by Parmscript\n#pragma once\n')
79 | header:write('#include \n#include \n#include \n#include \n\n')
80 | header:write(beginnamespace)
81 | header:write(ps.cppStruct())
82 | header:write('\n')
83 | if outputcpp then
84 | header:write(fmt('bool ImGuiInspect(%s&, std::unordered_set&);\n', name))
85 | header:write('\n')
86 | end
87 | header:write(endnamespace)
88 | header:close()
89 |
90 | printf('writing impl to "%s"', implpath)
91 | local impl=io.open(implpath, 'w')
92 | impl:write('//Generated by Parmscript\n')
93 | if outputcpp then
94 | impl:write(fmt('#include "%s"\n', name:lower()..'.h'))
95 | impl:write('#include \n#include \n')
96 | end
97 | impl:write(beginnamespace)
98 | impl:write(ps.imguiInspector())
99 | impl:write(endnamespace)
100 | impl:close()
101 | else
102 | printf('error: cannot parse input')
103 | end
104 |
105 |
106 |
--------------------------------------------------------------------------------
/parmscript/parmexpr.lua:
--------------------------------------------------------------------------------
1 | local fmt=string.format
2 | local map=function(f,t)
3 | local result={}
4 | for _,v in ipairs(t) do
5 | table.insert(result, f(v))
6 | end
7 | return result
8 | end
9 | local reduce=function(f,t,init)
10 | if #t==1 and init~=nil then
11 | return f(init, t[1])
12 | elseif #t<2 then
13 | return
14 | end
15 | local result=init~=nil and init or t[1]
16 | for i=init~=nil and 1 or 2, #t do
17 | result=f(result,t[i])
18 | end
19 | return result
20 | end
21 | local titleize=function(t)
22 | return string.gsub(t, '%w+', function(w) return w:sub(1,1):upper()..w:sub(2) end)
23 | end
24 | local dbgf=function(...)end
25 | --dbgf=function(...)print(fmt(...))end
26 |
27 | local loadParmScript=function(parmscript)
28 | local parmsetname = 'Parms'
29 | --[[
30 | fields: tree of parms
31 |
32 | each parm can be a leaf (field)
33 | or a branch (group or list)
34 | ]]
35 | local root = {name='', path='', type='struct', fields={}}
36 | local parmlut = {['']=root}
37 | local currentbranch = root -- root
38 | local path = '' -- `pwd` equivalent for current parm
39 | local objpath = {root} -- `pwd` of parms objects
40 | local typedefs={string='std::string'}
41 |
42 | local escape = function(name)
43 | name = string.gsub(name, '[^%w_]', '_')
44 | if name=='' or not string.match(name, '[%a_]%w*') then
45 | name = '_'..name
46 | end
47 | return name
48 | end
49 |
50 | local quoteString=function(str)
51 | return fmt('%q',str):gsub('\\\n','\\n')
52 | --[[
53 | return fmt('"%s"',
54 | string.gsub(
55 | str,
56 | '[%c"\']',
57 | function(c) return fmt('""\\x%02x""', string.byte(c)) end))
58 | ]]
59 | end
60 |
61 | local function fullpath(name)
62 | if path=='' then
63 | return name
64 | else
65 | return path..'.'..name
66 | end
67 | end
68 |
69 | local defineNonField=function(ui)
70 | return function(label)
71 | local fullname=fullpath('ui_'..ui)
72 | local field={name='ui_only', path=fullname, parent=currentbranch, type=nil, ui=ui}
73 | table.insert(currentbranch.fields, field)
74 | field.meta = {label = label}
75 | return function(meta)
76 | meta.label = label
77 | field.meta = meta
78 | end
79 | end
80 | end
81 |
82 | local defineField=function(t, ui)
83 | return function(name)
84 | assert(not string.find(name,'[^%w_]'), fmt("name should contain letters, digits and underscores only, got \"%s\".", name))
85 | local fullname=fullpath(name)
86 | local field={name=name, path=fullname, parent=currentbranch, type=t, ui=ui}
87 | table.insert(currentbranch.fields, field)
88 | if t and t~='' then
89 | assert(not parmlut[fullname], fmt('%q already exist', fullname))
90 | parmlut[fullname]=field
91 | end
92 | return function(meta)
93 | field.meta = meta
94 | end
95 | end
96 | end
97 |
98 | local enter=function(name, type, flat) -- enters dir, if flat then its fields are defined in the scope of parent
99 | dbgf('entering %s', name)
100 | local prevbranch = currentbranch
101 | assert(not string.find(name,'[^%w_]'), "name should contain letters, digits and underscores only.")
102 | if not flat then
103 | path=fullpath(name)
104 | assert(not parmlut[path], fmt('%s already exist', path))
105 | end
106 | local label=titleize(name)
107 | name = escape(name)
108 | currentbranch = {name=name, ui=type, type=type, path=path, flat=flat, parent=currentbranch, meta={label=label}, fields={}}
109 | if flat then
110 | parmlut[fullpath(name)] = currentbranch
111 | else
112 | parmlut[path] = currentbranch
113 | end
114 | table.insert(prevbranch.fields, currentbranch)
115 | table.insert(objpath, currentbranch)
116 | dbgf('path=%s, top=%s', path, currentbranch)
117 | return function(meta)
118 | currentbranch.meta = meta
119 | end
120 | end
121 |
122 | local leave=function(name)
123 | dbgf('leaving %s', name)
124 | if not currentbranch.flat then
125 | local lastdot = string.find(path, '%.[^.]+$')
126 | local leaf
127 | if lastdot then
128 | leaf = string.sub(path, lastdot+1)
129 | path=string.sub(path, 1, lastdot-1)
130 | else
131 | leaf = path
132 | path = ''
133 | end
134 | assert(leaf==name, 'enter/leave scope name mismatch')
135 | end
136 |
137 | assert(#objpath>1)
138 | local popobj=table.remove(objpath)
139 | assert(popobj.name==name, fmt('enter(%q)/leave(%q) scope name mismatch', popobj.name, name))
140 | --if not currentbranch.flat then
141 | -- dbgf('objpath=%s', table.concat(map(function(t) return t.name end, objpath), ' . '))
142 | -- assert(objpath[#objpath]==parmlut[path], fmt('%q mismatch with %q in lut', path, objpath[#objpath].path))
143 | --end
144 | currentbranch=objpath[#objpath]
145 | dbgf('path=%s', path)
146 | end
147 |
148 | local makeMenu=function(name)
149 | return defineField('menu', 'menu')(name)
150 | end
151 |
152 | local safeenv = {
153 | yes = true,
154 | no = false,
155 |
156 | parmset=function(name) parmsetname=name end,
157 | label=defineNonField('label'),
158 | separator=defineNonField('separator'),
159 | spacer=defineNonField('spacer'),
160 | toggle=defineField('bool', 'toggle'),
161 | int=defineField('int'),
162 | int2=defineField('int2'),
163 | float=defineField('float'),
164 | float2=defineField('float2'),
165 | float3=defineField('float3'),
166 | float4=defineField('float4'),
167 | double=defineField('double'),
168 | color=defineField('color'),
169 | text=defineField('string', 'text'),
170 | button=defineField('function','button'),
171 | menu=makeMenu, -- defineField('int', 'select'),
172 | combo=defineField('string', 'combo'),
173 | group=function(name) return enter(name, 'group', true) end,
174 | endgroup=leave,
175 | struct=function(name) return enter(name, 'struct') end,
176 | endstruct=leave,
177 | list=function(name) return enter(name, 'list') end,
178 | endlist=leave,
179 | pairs=pairs,
180 | ipairs=ipairs,
181 | alias=function(underlaying, inspector_tag, initial_meta)
182 | return function(name)
183 | local meta = {inspector=inspector_tag}
184 | if initial_meta then
185 | for i,v in pairs(initial_meta) do
186 | meta[i] = v
187 | end
188 | end
189 | local metasetter = underlaying(name)
190 | metasetter(meta)
191 | return function(moremeta)
192 | for i,v in pairs(moremeta) do
193 | meta[i] = v
194 | end
195 | metasetter(meta)
196 | end
197 | end
198 | end,
199 | }
200 | local parm=function(name)
201 | return parmlut[name]
202 | end
203 | local allParms=function()
204 | return parmlut
205 | end
206 |
207 | local tablelength=function(t)
208 | local len=0
209 | if type(t)=='table' then
210 | for i,v in pairs(t) do
211 | len = len+1
212 | end
213 | end
214 | return len
215 | end
216 |
217 | local function cppClassName(parm, fullname)
218 | local class = parm.meta and parm.meta.class
219 | if not class or class=='' then
220 | if parm.ui=='menu' and parm.meta.items and #parm.meta.items>0 then --enum
221 | class = fmt('menu_%s', escape(parm.name))
222 | else --struct
223 | class = fmt('%s_%s', parm.type, parm.name)
224 | end
225 | end
226 | if fullname then
227 | local t=parm.parent
228 | while t~=root do
229 | if not t.flat then
230 | class=cppClassName(t)..'::'..class
231 | end
232 | t=t.parent
233 | end
234 | class=parmsetname..'::'..class
235 | end
236 | return class
237 | end
238 |
239 | -- from parm path to variable name
240 | local function cppVarName(rootvar)
241 | return function(path)
242 | local field=parmlut[path]
243 | assert(field, fmt('cannot locate field %q', path))
244 | local varname = field.name
245 | local t=field.parent
246 | while t~=root do
247 | if not t.flat then
248 | varname=t.name..'.'..varname
249 | end
250 | t=t.parent
251 | end
252 | return rootvar..'.'..varname
253 | end
254 | end
255 |
256 | local function _genCppFields(branch, indent)
257 | local typeof = type
258 | local code=''
259 | indent = indent or 1
260 | local indentstr = string.rep(' ', indent*2)
261 | local emit=function(line)
262 | code=code..indentstr..line..'\n'
263 | end
264 | local emitf=function(line,...)
265 | code=code..indentstr..fmt(line,...)..'\n'
266 | end
267 | for _,v in pairs(branch.fields) do
268 | if not v.type or not v.name then
269 | dbgf('skipping %s', v.ui or v.label or v.name)
270 | goto bypass_field
271 | end
272 | local type = typedefs[v.type] or v.type
273 | local arr = type:match('%[%d+%]') or ''
274 | type = type:match('[%w:<>()]+')
275 | local default = v.meta and v.meta.default
276 | if v.fields then -- a branch node
277 | local class = cppClassName(v)
278 | if v.flat then
279 | code = code .. _genCppFields(v, indent)
280 | goto bypass_field
281 | else
282 | emitf('struct %s { // %s', class, v.type)
283 | code = code .. _genCppFields(v, indent+1)
284 | emit('};')
285 | end
286 | if v.type=='list' then
287 | type = fmt('std::vector<%s>', class)
288 | else --if v.type=='struct' then
289 | type = class
290 | end
291 | elseif v.ui=='menu' and v.meta.items and #v.meta.items>0 then
292 | local class = cppClassName(v)
293 | type = class
294 | emitf('enum class %s {', class)
295 | local nextvalue = 0
296 | for idx, item in ipairs(v.meta.items) do
297 | local label=v.meta.itemlabels and v.meta.itemlabels[idx]
298 | local labelcomment=label and fmt(' // label=%s', label) or ''
299 | local value=v.meta.itemvalues and v.meta.itemvalues[idx] or nextvalue
300 | emitf(' %s=%d,%s', item, value, labelcomment)
301 | nextvalue = value+1
302 | end
303 | emit('};')
304 | if default then
305 | default = class..'::'..default
306 | end
307 | elseif v.type=='' then
308 | goto bypass_field
309 | end
310 | if v.type=='string' and typeof(default)=='string' then
311 | default = quoteString(default)
312 | elseif typeof(default)=='table' then
313 | local tofloat = function(f)
314 | local s=tostring(f)
315 | if s:find('[.e]') then
316 | return s..'f'
317 | elseif s:match('%d+')==s then
318 | return s..'.0f'
319 | else
320 | return s
321 | end
322 | end
323 | if v.type=='color' then
324 | local solidalpha=''
325 | if v.type=='color' and v.meta and not v.meta.alpha and #default==3 then
326 | solidalpha=', 1.0f'
327 | end
328 | default = fmt('{%s%s}', table.concat(map(tofloat, default), ', '), solidalpha)
329 | else
330 | if v.type:find('float') then
331 | default = fmt('{%s}', table.concat(map(tofloat, default), ', '))
332 | else
333 | default = fmt('{%s}', table.concat(map(tostring, default), ', '))
334 | end
335 | end
336 | end
337 | if default then
338 | default = ' = '..tostring(default)
339 | else
340 | default = ''
341 | end
342 |
343 | local comment = {}
344 | local nmeta = tablelength(v.meta)
345 | local nthmeta = 1
346 | if v.ui then
347 | table.insert(comment, fmt('ui=%q', v.ui))
348 | end
349 | for k,m in pairs(v.meta or {}) do
350 | if typeof(m)=='table' or k=='default' then
351 | -- pass
352 | else
353 | table.insert(comment, fmt('%s=%q', k, m))
354 | end
355 | end
356 | if #comment>0 then
357 | emitf('%s %s%s%s; // %s', type, v.name, arr, default, table.concat(comment, ', '))
358 | else
359 | emitf('%s %s%s%s;', type, v.name, arr, default)
360 | end
361 | ::bypass_field::
362 | end
363 | return code
364 | end
365 |
366 | -- generate cpp structure
367 | local genCppStruct=function()
368 | local code = fmt('struct %s {\n', parmsetname)
369 | code = code.._genCppFields(root)
370 | code = code..'};\n'
371 | return code
372 | end
373 |
374 | local function _genImGuiInspector(rootvar, container, branch, indent, arrayidx)
375 | local typeof = type
376 | local code=''
377 | indent = indent or 1
378 | local indentstr = string.rep(' ', indent*2)
379 | local emit=function(line)
380 | code=code..indentstr..line..'\n'
381 | end
382 | local emitf=function(line,...)
383 | code=code..indentstr..fmt(line,...)..'\n'
384 | end
385 | local numericformat = {
386 | int='Int',
387 | int2='Int2',
388 | int3='Int3',
389 | int4='Int4',
390 | float='Float',
391 | float2='Float2',
392 | float3='Float3',
393 | float4='Float4',
394 | }
395 | for _,v in pairs(branch.fields) do
396 | local type = v.type
397 | local default = v.meta and v.meta.default
398 | local cannotjoin = false -- cannot join next
399 | local label=v.meta and v.meta.label or v.name
400 | local thisvar = container..'.'..v.name
401 | local disablewhen = v.meta and v.meta.disablewhen
402 | if disablewhen then
403 | local disableexpr = disablewhen:gsub('{([%w_.:]+)}', function(t)
404 | dbgf('gsub %s ..', t)
405 | local decoration=t:match('%w+:')
406 | if not decoration then
407 | return cppVarName(rootvar)(t)
408 | elseif decoration=='menu:' then
409 | t = t:sub(6)
410 | local n = t:match('::([%w_]+)')
411 | t = t:match('([%w_.]+)::')
412 | assert(parmlut[t], fmt('cannot find parm %q', t))
413 | return cppClassName(parmlut[t],true)..'::'..n
414 | elseif decoration=='length:' then
415 | t = t:sub(8)
416 | assert(parmlut[t], fmt('cannot find parm %q', t))
417 | assert(parmlut[t].type == 'list', fmt('%q is not a list', t))
418 | return t..'.size()'
419 | else
420 | assert(false, fmt('unknown decoration: %q', decoration))
421 | end
422 | end)
423 | emitf('ImGui::BeginDisabled(%s);', disableexpr)
424 | end
425 | if v.flat then
426 | thisvar = container
427 | end
428 | if arrayidx then
429 | emitf('std::string label_with_id_%s = %q"["+std::to_string(%s)+"]##%s";', v.name, label, arrayidx, v.name)
430 | label=fmt('label_with_id_%s.c_str()', v.name)
431 | else
432 | label = titleize(label)..'##'..v.name
433 | label=quoteString(label)
434 | end
435 | if _ == #branch.fields then
436 | cannotjoin = true
437 | end
438 | if v.fields then -- a branch node
439 | if v.type=='group' then
440 | local flags = v.meta and v.meta.closed and '0' or 'ImGuiTreeNodeFlags_DefaultOpen'
441 | emitf('if(ImGui::CollapsingHeader(%s, %s)) {', label, flags)
442 | code = code .. _genImGuiInspector(rootvar, thisvar, v, indent+1);
443 | emit('}')
444 | elseif v.type=='struct' then
445 | emitf('if(ImGui::TreeNodeEx(%s, ImGuiTreeNodeFlags_Framed)) {', label)
446 | code = code .. _genImGuiInspector(rootvar, thisvar, v, indent+1);
447 | emit(' ImGui::TreePop();')
448 | emit('}')
449 | elseif v.type=='list' then
450 | local countvar=fmt('list%s_cnt', v.name)
451 | emitf('int %s=static_cast((%s).size());', countvar, thisvar)
452 | emitf('if (ImGui::InputInt("# " %s, &%s)) {', label, countvar)
453 | emitf(' %s.resize(%s);', thisvar, countvar);
454 | emitf(' modified.insert(%q);', v.path)
455 | emit ('}')
456 | local listidx=fmt('list%s_idx', v.name)
457 | emitf('for(int %s=0; %s<%s; ++%s) {', listidx, listidx, countvar, listidx)
458 | code = code.._genImGuiInspector(rootvar, thisvar..'['..listidx..']', v, indent+1, listidx);
459 | emitf(' if (%s+1<%s) ImGui::Separator();', listidx, countvar)
460 | emit ('}')
461 | else
462 | emit(fmt('// TODO: unknown branch type %s', v.type))
463 | end
464 | cannotjoin = true
465 | elseif v.ui=='menu' and v.meta.items and #v.meta.items>0 then
466 | local class = cppClassName(v,true)
467 | local labels={}
468 | local values={}
469 | for idx, item in ipairs(v.meta.items) do
470 | local ilabel=v.meta.itemlabels and v.meta.itemlabels[idx]
471 | ilabel = ilabel or titleize(item)
472 | ilabel = quoteString(ilabel)
473 | table.insert(labels, ilabel)
474 | table.insert(values, fmt('%s::%s', class, item))
475 | end
476 | emitf('static const char* %s_labels[]={%s};', v.name, table.concat(labels, ", "))
477 | emitf('static const %s %s_values[]={%s};', class, v.name, table.concat(values, ", "))
478 | emitf('int current_item_%s = 0;', v.name)
479 | emitf('for(; current_item_%s < %d; ++current_item_%s)', v.name, #values, v.name)
480 | emitf(' if (%s_values[current_item_%s]==(%s)) break;',
481 | v.name, v.name, thisvar)
482 | emitf('if (ImGui::Combo(%s, ¤t_item_%s, %s_labels, %d)) {',
483 | label, v.name, v.name, #labels)
484 | emitf(' %s = %s_values[current_item_%s];', thisvar, v.name, v.name)
485 | emitf(' modified.insert(%q);', v.path)
486 | emit ('}')
487 |
488 | cannotjoin = true
489 | elseif v.ui=='toggle' then
490 | assert(v.type=='bool')
491 | emitf('if(ImGui::Checkbox(%s, &(%s))) modified.insert(%q);', label, thisvar, v.path)
492 | elseif v.ui=='button' then
493 | assert(v.type=='function')
494 | emitf('if(ImGui::Button(%s)) {', label)
495 | emitf(' if(%s) (%s)();', thisvar, thisvar)
496 | emitf(' modified.insert(%q);', v.path)
497 | emit ('}')
498 | elseif numericformat[v.type] then
499 | local ctl = numericformat[v.type]
500 | local addr = '&'..thisvar
501 | if typedefs[v.type] and typedefs[v.type]:find('%[%d+%]') then
502 | addr = fmt('(%s)', thisvar)
503 | else
504 | local convert = ''
505 | if v.type:find('[234]') then
506 | convert = fmt('reinterpret_cast<%s*>', v.type:match('%a+'))
507 | end
508 | addr = fmt('%s(&(%s))', convert, thisvar)
509 | end
510 | local min, max = v.meta and v.meta.min or 0, v.meta and v.meta.max or 1
511 | local minmax = ''
512 | if v.meta and v.meta.min and v.meta.max then
513 | if v.type:find('int') then
514 | minmax=fmt(', %d, %d', v.meta.min, v.meta.max)
515 | elseif v.type:find('float') then
516 | minmax=fmt(', %f, %f', v.meta.min, v.meta.max)
517 | end
518 | end
519 | local ui = v.meta and v.meta.ui or 'drag'
520 | if ui=='slider' or v.meta and (not v.meta.ui and v.meta.min and v.meta.max) then
521 | emitf('if(ImGui::Slider%s(%s, %s%s))',
522 | ctl, label, addr, minmax)
523 | elseif ui=='drag' then
524 | local spd=v.meta and v.meta.speed or 1.0
525 | emitf('if(ImGui::Drag%s(%s, %s, %ff%s))', ctl, label, addr, spd, minmax)
526 | else --input
527 | emitf('if(ImGui::Input%s(%s, %s))', ctl, label, addr)
528 | end
529 | emitf(' modified.insert(%q);', v.path)
530 | elseif v.type=='double' then
531 | emitf('if(ImGui::InputDouble(%s, &(%s)))', label, thisvar)
532 | emitf(' modified.insert(%q);', v.path)
533 | elseif v.type=='color' then
534 | local ctl = 'ColorEdit'
535 | local meta = v.meta or {}
536 | local alpha = true
537 | if meta.ui=='picker' then
538 | ctl = 'ColorPicker'
539 | end
540 | if meta.alpha==false then -- meta.alpha==nil implys true
541 | alpha = false
542 | end
543 | if alpha then
544 | ctl = ctl..'4'
545 | else
546 | ctl = ctl..'3'
547 | end
548 | local flags={}
549 | if alpha then
550 | flags={'AlphaBar', 'AlphaPreview', 'AlphaPreviewHalf'}
551 | else
552 | flags={'NoAlpha'}
553 | end
554 | if meta.hdr then table.insert(flags,'HDR') end
555 | table.insert(flags, meta.hsv and 'DisplayHSV' or 'DisplayRGB')
556 | table.insert(flags, (meta.float or meta.hdr) and 'Float' or 'Uint8')
557 | if meta.wheel then table.insert(flags,'PickerHueWheel') end
558 | local flagstring = table.concat(map(function(t) return 'ImGuiColorEditFlags_'..t end, flags), ' | ')
559 | if flagstring=='' then
560 | flagstring='0'
561 | end
562 | if typedefs[v.type] and typedefs[v.type]:match('float%[[34]%]') then
563 | emitf('if(ImGui::%s(%s, (%s), %s))', ctl, label, thisvar, flagstring)
564 | else
565 | emitf('if(ImGui::%s(%s, reinterpret_cast(&(%s)), %s))', ctl, label, thisvar, flagstring)
566 | end
567 | emitf(' modified.insert(%q);', v.path)
568 | elseif v.ui=='text' then
569 | assert(v.type=='string')
570 | if v.meta and v.meta.multiline then
571 | emitf('if(ImGui::InputTextMultiline(%s, &(%s)))', label, thisvar)
572 | else
573 | emitf('if(ImGui::InputText(%s, &(%s)))', label, thisvar)
574 | end
575 | emitf(' modified.insert(%q);', v.path)
576 | elseif v.ui=='label' then
577 | assert(not v.type or v.type=='')
578 | emitf('ImGui::TextUnformatted(%s);', quoteString(v.meta.label))
579 | elseif v.ui=='separator' then
580 | assert(not v.type or v.type=='')
581 | emit('ImGui::Separator();')
582 | elseif v.ui=='spacer' then
583 | assert(not v.type or v.type=='')
584 | emit('ImGui::Spacing();')
585 | else
586 | emitf('// TODO: unhandled: %s %s', v.type, v.name)
587 | end
588 |
589 | if disablewhen then
590 | emit('ImGui::EndDisabled();')
591 | end
592 | if v.meta and v.meta.joinnext and not cannotjoin then
593 | emit('ImGui::SameLine();')
594 | end
595 | end
596 | return code
597 | end
598 |
599 | local genImGuiInspector=function(var)
600 | var = var or 'parms'
601 | local code = fmt('bool ImGuiInspect(%s &%s, std::unordered_set& modified) {\n', parmsetname, var)
602 | code = code .. ' modified.clear();\n'
603 | code = code .. _genImGuiInspector(var, var, root)
604 | code = code .. ' return !modified.empty();\n'
605 | code = code .. '}\n'
606 | return code
607 | end
608 |
609 | local f, msg=load(parmscript,'parmscript','t',safeenv)
610 | if not f then
611 | return error(msg)
612 | end
613 | local result
614 | result, msg = pcall(f)
615 | if result then
616 | return {
617 | root=root,
618 | parm=parm,
619 | allParms=allParms,
620 | setTypedefs=function(td) typedefs=td end,
621 | typedef=function(a,b) typedefs[a]=b end,
622 | setUseBuiltinTypes=function()
623 | typedefs={['function']='std::function', string='std::string', float2='float[2]', float3='float[3]', color='float[4]'}
624 | end,
625 |
626 | parmsetName=function() return parmsetname end,
627 | cppStruct=genCppStruct,
628 | imguiInspector=genImGuiInspector,
629 | }
630 | else
631 | return error(msg)
632 | --return nil
633 | end
634 | end
635 |
636 | return loadParmScript
637 |
--------------------------------------------------------------------------------
/parmscript/parminspector.cpp:
--------------------------------------------------------------------------------
1 | #include "parminspector.h"
2 | #include
3 | #include
4 |
5 | extern "C" {
6 | #include
7 | #include
8 | #include
9 | }
10 |
11 | #include
12 | #include
13 | #include
14 |
15 | #ifdef DEBUG
16 | #include
17 | #define WARN(...) fprintf(stderr, __VA_ARGS__)
18 | #define INFO(...) fprintf(stdout, __VA_ARGS__)
19 | #else
20 | #define WARN(...) /*nothing*/
21 | #define INFO(...) /*nothing*/
22 | #endif
23 |
24 | namespace parmscript {
25 |
26 | hashmap ParmSetInspector::inspectorOverrides_;
27 |
28 | static std::string parmlabel(Parm const& parm)
29 | {
30 | return parm.label() + "##" + parm.path();
31 | }
32 |
33 | static bool boolFieldInspector(Parm& parm)
34 | {
35 | auto label = parmlabel(parm);
36 | bool v = parm.as();
37 | if (ImGui::Checkbox(label.c_str(), &v)) {
38 | parm.set(v);
39 | return true;
40 | }
41 | return false;
42 | }
43 |
44 | template
45 | struct ImGuiDataTypeTrait {};
46 | template <> struct ImGuiDataTypeTrait { static constexpr int value = ImGuiDataType_S32; };
47 | template <> struct ImGuiDataTypeTrait { static constexpr int value = ImGuiDataType_U32; };
48 | template <> struct ImGuiDataTypeTrait { static constexpr int value = ImGuiDataType_S64; };
49 | template <> struct ImGuiDataTypeTrait { static constexpr int value = ImGuiDataType_U64; };
50 | template <> struct ImGuiDataTypeTrait { static constexpr int value = ImGuiDataType_Float; };
51 | template <> struct ImGuiDataTypeTrait { static constexpr int value = ImGuiDataType_Double; };
52 |
53 | template
54 | bool scalarFieldInspector(Parm& parm)
55 | {
56 | constexpr int numcomponent = sizeof(valuetype) / sizeof(elemtype);
57 | constexpr int scalartype = ImGuiDataTypeTrait::value;
58 | bool imdirty = false;
59 | auto v = parm.as();
60 | auto ui = parm.getMeta("ui", "drag");
61 | auto min = parm.getMeta("min", elemtype(defaultmin));
62 | auto max = parm.getMeta("max", elemtype(defaultmax));
63 | auto speed = parm.getMeta("speed", 1);
64 | auto label = parmlabel(parm);
65 | void* pdata = &v;
66 | if (ui == "drag") {
67 | imdirty = ImGui::DragScalarN(label.c_str(), scalartype, pdata, numcomponent, speed, &min, &max);
68 | } else if (ui == "slider") {
69 | imdirty = ImGui::SliderScalarN(label.c_str(), scalartype, pdata, numcomponent, &min, &max);
70 | } else {
71 | imdirty = ImGui::InputScalarN(label.c_str(), scalartype, pdata, numcomponent);
72 | }
73 | if (imdirty)
74 | parm.set(v);
75 | return imdirty;
76 | }
77 |
78 | bool stringFieldInspector(Parm& parm)
79 | {
80 | bool imdirty = false;
81 | auto* v = parm.getPtr();
82 | auto label = parmlabel(parm);
83 | bool multiline = parm.getMeta("multiline", false);
84 | if (multiline)
85 | imdirty = ImGui::InputTextMultiline(label.c_str(), v, ImVec2(0,0), ImGuiInputTextFlags_EnterReturnsTrue);
86 | else
87 | imdirty = ImGui::InputText(label.c_str(), v, ImGuiInputTextFlags_EnterReturnsTrue);
88 | return imdirty;
89 | }
90 |
91 | bool colorFieldInspector(Parm& parm)
92 | {
93 | bool imdirty = false;
94 | auto label = parmlabel(parm);
95 | auto v = parm.as();
96 | bool alpha = parm.getMeta("alpha", false);
97 | bool hsv = parm.getMeta("hsv", false);
98 | bool hdr = parm.getMeta("hdr", false);
99 | bool wheel = parm.getMeta("wheel", false);
100 | bool picker = parm.getMeta("picker", false);
101 |
102 | uint32_t flags = 0;
103 | if (alpha)
104 | flags |= ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
105 | else
106 | flags |= ImGuiColorEditFlags_NoAlpha;
107 |
108 | if (hsv)
109 | flags |= ImGuiColorEditFlags_DisplayHSV;
110 | else
111 | flags |= ImGuiColorEditFlags_DisplayRGB;
112 |
113 | if (hdr)
114 | flags |= ImGuiColorEditFlags_Float;
115 | else
116 | flags |= ImGuiColorEditFlags_Uint8;
117 |
118 | if (wheel)
119 | flags |= ImGuiColorEditFlags_PickerHueWheel;
120 |
121 | if (alpha) {
122 | if (picker)
123 | imdirty = ImGui::ColorPicker4(label.c_str(), &v.r, flags);
124 | else
125 | imdirty = ImGui::ColorEdit4(label.c_str(), &v.r, flags);
126 | } else {
127 | if (picker)
128 | imdirty = ImGui::ColorPicker3(label.c_str(), &v.r, flags);
129 | else
130 | imdirty = ImGui::ColorEdit3(label.c_str(), &v.r, flags);
131 | }
132 | if (imdirty)
133 | parm.set(v);
134 | return imdirty;
135 | }
136 |
137 | bool ParmSetInspector::inspect(Parm& parm, hashset& modified, lua_State* L, ParmFonts* fonts)
138 | {
139 | bool imdirty = false;
140 | bool displayChildren = true;
141 | bool fontPushed = false;
142 | bool itemWidthPushed = false;
143 | auto label = parmlabel(parm);
144 |
145 | auto disablewhen = parm.getMeta("disablewhen", "");
146 | if (fonts) {
147 | auto font = parm.getMeta("font", "regular");
148 | if (font == "regular" && fonts->regular) {
149 | ImGui::PushFont(fonts->regular);
150 | fontPushed = true;
151 | } else if (font == "mono" && fonts->mono) {
152 | ImGui::PushFont(fonts->mono);
153 | fontPushed = true;
154 | }
155 | }
156 | if (int widthmeta = 0; parm.tryGetMeta("width", &widthmeta)) {
157 | ImGui::PushItemWidth(widthmeta);
158 | itemWidthPushed = true;
159 | }
160 | if (!disablewhen.empty()) {
161 | // expand {path.to.parm} to its value
162 | // expand {menu:path.to.parm::item} to its value
163 | // expand {length:path.to.parm} to its value
164 | // translate != into ~=, || into or, && into and, ! into not
165 | // evaluate disablewhen expr in Lua
166 |
167 | // init the eval function:
168 | bool disabled = false;
169 |
170 | if (L == nullptr)
171 | L = parmset_->defaultLuaRuntime();
172 | sol::state_view lua{L};
173 | auto loaded = lua.load(R"LUA(
174 | local ps, evalParm, expr=...
175 | return expr:gsub('{([^}]+)}', function(expr)
176 | local e = evalParm(ps, expr)
177 | if e~=nil then
178 | return string.format("%q", e)
179 | else
180 | return '{error}'
181 | end
182 | end):gsub('!=', '~='):gsub('||', ' or '):gsub('&&', ' and '):gsub('!', 'not ')
183 | )LUA");
184 | if (loaded.valid()) {
185 | std::string expanded = loaded.call(parm.root(), ParmSet::evalParm, disablewhen);
186 | // INFO("disablewhen \"%s\" expanded to \"%s\"\n", disablewhen.c_str(), expanded.c_str());
187 | if (expanded.find("{error}") == std::string::npos) {
188 | loaded = lua.load("return "+expanded, "disablewhen", sol::load_mode::text);
189 | if (loaded.valid()) {
190 | disabled = loaded.call();
191 | }
192 | }
193 | } else {
194 | WARN("failed to load disablewhen script");
195 | }
196 |
197 | ImGui::BeginDisabled(disabled);
198 | }
199 |
200 | auto ui = parm.ui();
201 | using ui_type_enum = Parm::ui_type_enum;
202 | using value_type_enum = Parm::value_type_enum;
203 | if (ui == ui_type_enum::FIELD) {
204 | imdirty = getFieldInspector(parm)(parm);
205 | } else if (ui == Parm::ui_type_enum::GROUP) {
206 | if (!ImGui::CollapsingHeader(label.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) {
207 | displayChildren = false;
208 | }
209 | } else if (ui == Parm::ui_type_enum::STRUCT) {
210 | if (!ImGui::TreeNodeEx(label.c_str(), ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_DefaultOpen)) {
211 | displayChildren = false;
212 | }
213 | } else if (ui == Parm::ui_type_enum::LIST) {
214 | displayChildren = false;
215 | int numitems = parm.numListValues();
216 | if (ImGui::InputInt(("# "+label).c_str(), &numitems)) {
217 | parm.resizeList(numitems);
218 | modified.insert(parm.path());
219 | imdirty = true;
220 | }
221 | for (int i=0; iallFields()) {
223 | imdirty |= inspect(*field, modified, L, fonts);
224 | }
225 | if (i+1 labels;
241 | labels.reserve(parm.menuLabels().size());
242 | for (auto const& label: parm.menuLabels()) {
243 | labels.push_back(label.c_str());
244 | }
245 | if (ImGui::Combo(label.c_str(), parm.getPtr(), labels.data(), labels.size()))
246 | imdirty = true;
247 | } else {
248 | INFO("unknown ui %s of type %d\n", parm.name().c_str(), static_cast(ui));
249 | }
250 |
251 | if (displayChildren && parm.numFields() != 0) {
252 | for (auto child: parm.allFields())
253 | imdirty |= inspect(*child, modified, L, fonts);
254 | }
255 | if (ui == ui_type_enum::STRUCT && displayChildren) {
256 | ImGui::TreePop();
257 | }
258 |
259 | if (itemWidthPushed)
260 | ImGui::PopItemWidth();
261 | if (fontPushed)
262 | ImGui::PopFont();
263 | if (!disablewhen.empty()) {
264 | ImGui::EndDisabled();
265 | }
266 | if (imdirty) {
267 | modified.insert(parm.path());
268 | if (ui != ui_type_enum::BUTTON) {
269 | edited_ = true;
270 | if (ImGui::IsMouseDown(ImGuiMouseButton_Left))
271 | editing_ = true;
272 | }
273 | }
274 | if (editing_ && !ImGui::IsMouseDown(ImGuiMouseButton_Left))
275 | editing_ = false;
276 | if (parm.getMeta("joinnext", false))
277 | ImGui::SameLine();
278 | return imdirty;
279 | }
280 |
281 | FieldInspector ParmSetInspector::getFieldInspector(Parm const& parm)
282 | {
283 | auto inspector = parm.getMeta("inspector", "");
284 | if (inspector != "") {
285 | if (auto itr = inspectorOverrides_.find(inspector); itr != inspectorOverrides_.end())
286 | return itr->second;
287 | }
288 | using value_type_enum = Parm::value_type_enum;
289 | switch(parm.type()) {
290 | case value_type_enum::BOOL:
291 | return boolFieldInspector;
292 | case value_type_enum::INT:
293 | return scalarFieldInspector;
294 | case value_type_enum::INT2:
295 | return scalarFieldInspector;
296 | case value_type_enum::FLOAT:
297 | return scalarFieldInspector;
298 | case value_type_enum::FLOAT2:
299 | return scalarFieldInspector;
300 | case value_type_enum::FLOAT3:
301 | return scalarFieldInspector;
302 | case value_type_enum::FLOAT4:
303 | return scalarFieldInspector;
304 | case value_type_enum::DOUBLE:
305 | return scalarFieldInspector;
306 | case value_type_enum::STRING:
307 | return stringFieldInspector;
308 | case value_type_enum::COLOR:
309 | return colorFieldInspector;
310 | }
311 | return [](Parm& parm)->bool {
312 | WARN("dow\'t know how to inspect parm \"%s\"\n", parm.path().c_str());
313 | return false;
314 | };
315 | }
316 |
317 | void ParmSetInspector::loadParmScript(std::string_view script)
318 | {
319 | auto newparms = std::make_unique();
320 | newparms->loadScript(script);
321 | parmset_.swap(newparms);
322 | }
323 |
324 | bool ParmSetInspector::inspect(lua_State* L, ParmFonts* fonts)
325 | {
326 | if (!parmset_)
327 | return false;
328 | if (L == nullptr)
329 | L = parmset_->defaultLuaRuntime();
330 | parmset_->clearDirtyEntries();
331 | for (auto child: parmset_->root_->allFields())
332 | inspect(*child, parmset_->dirtyEntries_, L, fonts);
333 | edited_ |= !parmset_->dirtyEntries_.empty();
334 | return !parmset_->dirtyEntries_.empty();
335 | }
336 |
337 | }
338 |
339 |
--------------------------------------------------------------------------------
/parmscript/parminspector.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "parmscript.h"
4 |
5 | struct ImFont;
6 | struct ParmFonts
7 | {
8 | ImFont* regular;
9 | ImFont* mono;
10 | };
11 |
12 | namespace parmscript {
13 |
14 | using FieldInspector = std::function;
15 |
16 | class ParmSetInspector final
17 | {
18 | ParmSetInspector(ParmSetInspector const&) = delete;
19 | protected:
20 | bool edited_ = false;
21 | bool editing_ = false;
22 | std::unique_ptr parmset_;
23 | static hashmap inspectorOverrides_;
24 |
25 | bool inspect(Parm& parm, hashset& dirty, lua_State* L = nullptr, ParmFonts* fonts = nullptr);
26 |
27 | public:
28 | ParmSetInspector()
29 | {
30 | parmset_ = std::make_unique();
31 | }
32 | static void setFieldInspector(string const& name, FieldInspector f)
33 | {
34 | inspectorOverrides_[name] = std::move(f);
35 | }
36 | static FieldInspector getFieldInspector(Parm const& parm);
37 |
38 | void setParms(std::unique_ptr parms) { parmset_ = std::move(parms); }
39 | void loadParmScript(std::string_view script);
40 | auto& parms() { return *parmset_; }
41 | auto getParm(string const& name) -> ParmPtr
42 | {
43 | if (empty()) return nullptr;
44 | return parmset_->get(name);
45 | }
46 | auto const& parms() const { return *parmset_; }
47 | bool empty() const { return !parmset_ || !parmset_->loaded(); }
48 |
49 | bool inspect(lua_State* L=nullptr, ParmFonts* fonts=nullptr);
50 | auto const& dirtyEntries() const { return parmset_->dirtyEntries(); }
51 | bool doneEditing() const { return edited_ && !editing_; } // supposed to be used as save points
52 | bool edited() const { return edited_; }
53 | bool dirty() const { return edited_; }
54 | void markClean() { parmset_->clearDirtyEntries(); edited_ = false; } // when saved, remember to reset this
55 | };
56 |
57 | } // namespace parmscript
58 |
59 |
--------------------------------------------------------------------------------
/parmscript/parmscript.cpp:
--------------------------------------------------------------------------------
1 | #include "parmscript.h"
2 |
3 | #include
4 | #include
5 |
6 | extern "C" {
7 | #include
8 | #include
9 | #include
10 | }
11 |
12 | #include
13 |
14 | static const char parmexpr_src[] = {
15 | #include
16 | };
17 |
18 | #ifdef DEBUG
19 | #include
20 | #define WARN(...) fprintf(stderr, __VA_ARGS__)
21 | #define INFO(...) fprintf(stdout, __VA_ARGS__)
22 | #else
23 | #define WARN(...) /*nothing*/
24 | #define INFO(...) /*nothing*/
25 | #endif
26 |
27 | namespace parmscript {
28 |
29 | ParmPtr Parm::getField(string const& relpath) {
30 | if (auto dot=relpath.find('.'); dot!=string::npos) {
31 | if (auto f=getField(relpath.substr(0, dot)))
32 | return f->getField(relpath.substr(dot+1));
33 | else
34 | return nullptr;
35 | } else {
36 | string childname = relpath;
37 | auto idxstart = relpath.find('[');
38 | int idx = -1;
39 | if (idxstart!=string::npos) {
40 | auto idxend = relpath.find(']');
41 | if (idxend==string::npos)
42 | return nullptr;
43 | string idxstr = relpath.substr(idxstart+1, idxend-idxstart-1);
44 | idx = std::stoi(idxstr);
45 | childname = relpath.substr(0, idxstart);
46 | }
47 | if (auto f = std::find_if(fields_.begin(), fields_.end(), [&childname](ParmPtr p){
48 | return p->name()==childname;
49 | });
50 | f!=fields_.end()) {
51 | if (idxstart!=string::npos) {
52 | if (idx>=0 && idx<(*f)->listValues_.size()) {
53 | return (*f)->listValues_[idx];
54 | }
55 | } else {
56 | return *f;
57 | }
58 | }
59 | for (auto f : fields_) {
60 | if (f->ui()==ui_type_enum::GROUP) { // group members are in current namespace
61 | if (auto gf = f->getField(relpath))
62 | return gf;
63 | }
64 | }
65 | }
66 | return nullptr;
67 | }
68 |
69 | void Parm::resizeList(size_t cnt)
70 | {
71 | root_->dirtyEntries_.insert(path());
72 | if (auto oldsize=listValues_.size(); oldsize(root_);
75 | string indexstr = "["+std::to_string(i)+"]";
76 | newItem->setUI(ui_type_enum::STRUCT);
77 | newItem->setPath(path_+indexstr);
78 | listValues_.push_back(newItem);
79 | for (auto f: fields_) {
80 | auto newField = std::make_shared(*f);
81 | newField->setPath(newItem->path()+"."+f->name());
82 | newField->setLabel(newField->label()+indexstr);
83 | newItem->fields_.push_back(newField);
84 | }
85 | }
86 | } else {
87 | listValues_.resize(cnt);
88 | }
89 | }
90 |
91 | //////////////////////// ParmSet /////////////////////////////
92 |
93 | string& ParmSet::preloadScript()
94 | {
95 | static string script_;
96 | return script_;
97 | }
98 |
99 | int ParmSet::processLuaParm(lua_State* lua)
100 | {
101 | sol::state_view L{lua};
102 | auto self = sol::stack::get(lua, 1);
103 | auto parentid = sol::stack::get(lua, 2);
104 | auto field = sol::stack::get(L, 3);
105 | if (parentid<0 || !field) {
106 | WARN("bad argument passed to processLuaParm()\n");
107 | return 0;
108 | }
109 | string ui = field["ui"];
110 | string path = field["path"];
111 | string name = field["name"];
112 | string type = field["type"];
113 | sol::table meta = field["meta"];
114 | string label = meta["label"].get_or(Parm::titleize(name));
115 | auto defaultfield = meta["default"];
116 | Parm::value_type defaultval;
117 | INFO("processing field label(%s) ui(%s) type(%s) name(%s) ... ", label.c_str(), ui.c_str(), type.c_str(), name.c_str());
118 |
119 | auto parent = self->parms_[parentid];
120 | auto newparm = std::make_shared(Parm(self));
121 |
122 | Parm::ui_type_enum uitype = Parm::ui_type_enum::FIELD;
123 | if (ui=="label") uitype=Parm::ui_type_enum::LABEL;
124 | else if (ui=="separator") uitype=Parm::ui_type_enum::SEPARATOR;
125 | else if (ui=="spacer") uitype=Parm::ui_type_enum::SPACER;
126 | else if (ui=="button") uitype=Parm::ui_type_enum::BUTTON;
127 | else if (ui=="menu") uitype=Parm::ui_type_enum::MENU;
128 | else if (ui=="group") uitype=Parm::ui_type_enum::GROUP;
129 | else if (ui=="struct") uitype=Parm::ui_type_enum::STRUCT;
130 | else if (ui=="list") uitype=Parm::ui_type_enum::LIST;
131 |
132 | auto parseminmax = [&meta, &newparm](auto t) {
133 | using T = decltype(t);
134 | if (meta["min"].valid())
135 | newparm->setMeta("min", meta["min"].get());
136 | if (meta["max"].valid())
137 | newparm->setMeta("max", meta["max"].get());
138 | if (meta["speed"].valid())
139 | newparm->setMeta("speed", meta["speed"].get());
140 | if (!meta["ui"].valid() && meta["min"].valid() && meta["max"].valid())
141 | newparm->setMeta("ui", "slider");
142 | };
143 | auto boolmeta = [&meta, &newparm](string const& key) {
144 | if (meta[key].valid())
145 | newparm->setMeta(key, meta[key].get());
146 | };
147 | auto strmeta = [&meta, &newparm](string const& key) {
148 | if (meta[key].valid())
149 | newparm->setMeta(key, meta[key].get());
150 | };
151 |
152 | INFO("1 ");
153 |
154 | Parm::value_type_enum valuetype = Parm::value_type_enum::NONE;
155 | if (type=="bool") {
156 | valuetype = Parm::value_type_enum::BOOL;
157 | defaultval = defaultfield.get_or(false);
158 | } else if (type=="int") {
159 | valuetype = Parm::value_type_enum::INT;
160 | defaultval = defaultfield.get_or(0);
161 | parseminmax(0);
162 | } else if (type=="int2") {
163 | valuetype = Parm::value_type_enum::INT2;
164 | auto vals = defaultfield.get_or(std::array{0,0});
165 | defaultval = Parm::int2{vals[0], vals[1]};
166 | parseminmax(0);
167 | } else if (type=="float") {
168 | valuetype = Parm::value_type_enum::FLOAT;
169 | defaultval = defaultfield.get_or(0.f);
170 | parseminmax(0.f);
171 | } else if (type=="float2") {
172 | valuetype = Parm::value_type_enum::FLOAT2;
173 | auto vals = defaultfield.get_or(std::array{0,0});
174 | defaultval = Parm::float2{vals[0], vals[1]};
175 | parseminmax(0.f);
176 | } else if (type=="float3") {
177 | valuetype = Parm::value_type_enum::FLOAT3;
178 | auto vals = defaultfield.get_or(std::array{0,0,0});
179 | defaultval = Parm::float3{vals[0], vals[1], vals[2]};
180 | parseminmax(0.f);
181 | } else if (type=="float4") {
182 | valuetype = Parm::value_type_enum::FLOAT4;
183 | auto vals = defaultfield.get_or(std::array{0,0,0});
184 | defaultval = Parm::float4{vals[0], vals[1], vals[2], vals[3]};
185 | parseminmax(0.f);
186 | } else if (type=="color") {
187 | valuetype = Parm::value_type_enum::COLOR;
188 | auto vals = defaultfield.get_or(std::array{1,1,1,1});
189 | defaultval = Parm::color{vals[0], vals[1], vals[2], vals[3]};
190 | boolmeta("alpha");
191 | boolmeta("hsv");
192 | boolmeta("hdr");
193 | boolmeta("wheel");
194 | boolmeta("picker");
195 | } else if (type=="string") {
196 | valuetype = Parm::value_type_enum::STRING;
197 | defaultval.emplace(defaultfield.get_or(string("")));
198 | boolmeta("multiline");
199 | } else if (type=="double") {
200 | valuetype = Parm::value_type_enum::DOUBLE;
201 | defaultval.emplace(defaultfield.get_or(0.0));
202 | }
203 | boolmeta("joinnext");
204 | if (meta["width"].valid())
205 | newparm->setMeta("width", meta["width"].get());
206 | strmeta("ui");
207 | strmeta("disablewhen");
208 | strmeta("font");
209 | // any other none-predefined meta:
210 | meta.for_each([&newparm](sol::object key, sol::object val) {
211 | auto strkey = key.as();
212 | if (newparm->hasMeta(strkey))
213 | return;
214 | switch (val.get_type())
215 | {
216 | case sol::type::string:
217 | newparm->setMeta(strkey, val.as()); break;
218 | case sol::type::boolean:
219 | newparm->setMeta(strkey, val.as()); break;
220 | case sol::type::number:
221 | newparm->setMeta(strkey, val.as()); break;
222 | default:
223 | break;
224 | }
225 | });
226 | INFO("2 ");
227 | newparm->setup(name, path, label, uitype, valuetype, defaultval);
228 |
229 | if (uitype == Parm::ui_type_enum::MENU) {
230 | auto items = meta["items"].get_or(std::vector());
231 | auto labels = meta["itemlabels"].get_or(std::vector());
232 | auto values = meta["itemvalues"].get_or(std::vector());
233 | string nativedefault = "";
234 | if (!items.empty())
235 | nativedefault = items.front();
236 | std::string strdefault = defaultfield.get_or(nativedefault);
237 | auto itrdefault = std::find(items.begin(), items.end(), strdefault);
238 | int idxdefault = 0;
239 | if (itrdefault != items.end())
240 | idxdefault = itrdefault-items.begin();
241 | newparm->setMenu(items, idxdefault, labels, values);
242 | }
243 | INFO("3 ");
244 | parent->addField(newparm);
245 | self->parms_.push_back(newparm);
246 | int newid = self->parms_.size()-1;
247 | sol::stack::push(lua, newid);
248 | INFO("done.\n");
249 | return 1;
250 | }
251 |
252 | int ParmSet::pushParmValueToLuaStack(lua_State* L, ParmPtr parm)
253 | {
254 | if (parm->ui()==Parm::ui_type_enum::FIELD) {
255 | switch (parm->type()) {
256 | case Parm::value_type_enum::BOOL:
257 | sol::stack::push(L, parm->as());
258 | break;
259 | case Parm::value_type_enum::INT:
260 | sol::stack::push(L, parm->as());
261 | break;
262 | case Parm::value_type_enum::FLOAT:
263 | sol::stack::push(L, parm->as());
264 | break;
265 | case Parm::value_type_enum::DOUBLE:
266 | sol::stack::push(L, parm->as());
267 | break;
268 | case Parm::value_type_enum::STRING:
269 | sol::stack::push(L, parm->as());
270 | break;
271 | case Parm::value_type_enum::COLOR: {
272 | auto c = parm->as();
273 | sol::stack::push(L, std::array{c.r, c.g, c.b, c.a});
274 | break;
275 | }
276 | case Parm::value_type_enum::FLOAT2: {
277 | auto v = parm->as();
278 | sol::stack::push(L, std::array{v.x, v.y});
279 | break;
280 | }
281 | case Parm::value_type_enum::FLOAT3: {
282 | auto v = parm->as();
283 | sol::stack::push(L, std::array{v.x, v.y, v.z});
284 | break;
285 | }
286 | case Parm::value_type_enum::FLOAT4: {
287 | auto v = parm->as();
288 | sol::stack::push(L, std::array{v.x, v.y, v.z, v.w});
289 | break;
290 | }
291 | default:
292 | WARN("evalParm: type not supported\n");
293 | return 0;
294 | }
295 | return 1;
296 | } else if (parm->ui()==Parm::ui_type_enum::MENU) {
297 | sol::stack::push(L, parm->as());
298 | return 1;
299 | } else if (parm->ui()==Parm::ui_type_enum::STRUCT) {
300 | lua_createtable(L, 0, parm->numFields());
301 | for (int f=0, nf=parm->numFields(); ffields_[f]) == 0)
303 | lua_pushnil(L);
304 | lua_setfield(L, -2, parm->fields_[f]->name().c_str());
305 | }
306 | return 1;
307 | } else if (parm->ui()==Parm::ui_type_enum::LIST) {
308 | lua_createtable(L, parm->numListValues(), 0);
309 | for (int i=0, n=parm->numListValues(); ilistValues_[i]);
311 | lua_seti(L, -2, i+1);
312 | }
313 | return 1;
314 | } else {
315 | WARN("don\'t known how to handle parm \"%s\" of type %d\n", parm->name().c_str(), static_cast(parm->ui()));
316 | }
317 | return 0;
318 | }
319 |
320 | int ParmSet::evalParm(lua_State* L)
321 | {
322 | sol::state_view lua{L};
323 | auto optself = sol::stack::check_get(L, 1);
324 | auto optexpr = sol::stack::check_get(L, 2);
325 | if (!optself.has_value() || !optexpr.has_value()) {
326 | return luaL_error(L, "wrong arguments passed to ParmSet:evalParm, expected (ParmSet, string)");
327 | }
328 | auto* self = optself.value();
329 | auto& expr = optexpr.value();
330 |
331 | if (expr.find("menu:")==0) {
332 | expr = expr.substr(5);
333 | auto sep = expr.find("::");
334 | if (sep == string::npos)
335 | return 0;
336 | auto path = expr.substr(0, sep);
337 | auto name = expr.substr(sep+2);
338 | if (auto parm = self->get(path)) {
339 | // just a check
340 | if (parm->ui() != Parm::ui_type_enum::MENU)
341 | return 0;
342 | sol::stack::push(L, name);
343 | return 1;
344 | } else {
345 | return 0;
346 | }
347 | } else if (expr.find("length:")==0) {
348 | expr = expr.substr(7);
349 | if (auto parm = self->get(expr)) {
350 | if (parm->ui() == Parm::ui_type_enum::LIST) {
351 | sol::stack::push(L, parm->numListValues());
352 | return 1;
353 | }
354 | }
355 | return 0;
356 | }
357 |
358 | if (auto parm = self->get(expr)) {
359 | return pushParmValueToLuaStack(L, parm);
360 | }
361 | WARN("evalParm: \"%s\" cannot be evaluated\n", expr.c_str());
362 | return 0;
363 | }
364 |
365 | void ParmSet::loadScript(std::string_view sv, lua_State* L)
366 | {
367 | loaded_ = false;
368 | if (L == nullptr)
369 | L = defaultLuaRuntime();
370 | int luasp = lua_gettop(L); // stack pointer
371 | if (LUA_OK != luaL_loadbufferx(L, parmexpr_src, sizeof(parmexpr_src)-1, "parmexpr", "t")) {
372 | throw LoadError("failed to load parmexpr\n");
373 | return;
374 | }
375 | if (LUA_OK != lua_pcall(L, 0, 1, 0)) {
376 | lua_settop(L, luasp);
377 | throw LoadError("failed to call parmexpr\n");
378 | return;
379 | }
380 | auto fullscript = preloadScript();
381 | fullscript += "\n";
382 | fullscript += sv;
383 | lua_pushlstring(L, fullscript.data(), fullscript.size());
384 | if (LUA_OK != lua_pcall(L, 1, 1, 0)) {
385 | std::string message = luaL_optstring(L, -1, "unknown");
386 | lua_settop(L, luasp);
387 | throw LoadError(message);
388 | return;
389 | }
390 | root_ = std::make_shared(nullptr);
391 | root_->setUI(Parm::ui_type_enum::STRUCT);
392 | parms_ = {root_};
393 |
394 | sol::state_view lua{L};
395 | auto loaded = lua.load(R"LUA(
396 | local parmscript, cpp, process = ...
397 | local function dofield(cpp, parentid, field)
398 | local id = process(cpp, parentid, field)
399 | if field.fields and #field.fields > 0 then
400 | for _, v in pairs(field.fields) do
401 | dofield(cpp, id, v)
402 | end
403 | end
404 | end
405 |
406 | for _,v in pairs(parmscript.root.fields) do
407 | dofield(cpp, 0, v)
408 | end
409 | )LUA");
410 | if (loaded.valid()) {
411 | lua_pushvalue(L, -2); // return value of last `pcall` left on stack, which is the parmscript object
412 | sol::stack::push(L, this);
413 | lua_pushcfunction(L, processLuaParm);
414 | if (LUA_OK != lua_pcall(L, 3, 0, 0)) {
415 | std::string message = luaL_optstring(L, -1, "unknown");
416 | lua_settop(L, luasp);
417 | throw LoadError(message);
418 | return;
419 | } else {
420 | // done. pop the parmscript object from stack
421 | loaded_ = true;
422 | lua_pop(L, 1);
423 | }
424 | } else {
425 | throw LoadError("failed to load finalizing script\n");
426 | }
427 | loaded_ = true;
428 | }
429 |
430 | void ParmSet::exposeToLua(lua_State *L)
431 | {
432 | lua_CFunction luaopen_parmset = [](lua_State *L)->int {
433 | sol::state_view lua{L};
434 | auto ut = lua.new_usertype("ParmSet");
435 | ut.set("loadScript", [](lua_State *L)->int{
436 | auto optself = sol::stack::check_get(L, 1);
437 | auto optsrc = sol::stack::check_get(L, 2);
438 | if (!optself.has_value() || !optsrc.has_value()) {
439 | return luaL_error(L, "wrong arguments passed to ParmSet:loadScript, expected (ParmSet, string)");
440 | }
441 | if (lua_gettop(L)>2) {
442 | WARN("extra arguments passed to ParmSet:loadScript are discarded\n");
443 | }
444 | try {
445 | optself.value()->loadScript(optsrc.value(), L);
446 | } catch (std::exception const& e) {
447 | return luaL_error(L, "failed to load: %s", e.what());
448 | }
449 | return 0;
450 | });
451 | //ut.set("updateInspector", [](lua_State *L)->int{
452 | // auto optself = sol::stack::check_get(L, 1);
453 | // if (!optself.has_value()) {
454 | // return luaL_error(L, "wrong arguments passed to ParmSet:loadScript, expected (ParmSet)");
455 | // }
456 | // if (lua_gettop(L)>1) {
457 | // WARN("extra arguments passed to ParmSet:updateInspector are discarded\n");
458 | // }
459 | // sol::stack::push(L, optself.value()->updateInspector(L));
460 | // return 1;
461 | //});
462 | //ut.set("dirtyEntries", [](lua_State *L)->int{
463 | // auto optself = sol::stack::check_get(L, 1);
464 | // if (!optself.has_value()) {
465 | // return luaL_error(L, "wrong arguments passed to ParmSet:dirtyEntries, expected (ParmSet)");
466 | // }
467 | // auto const& dirty = optself.value()->dirtyEntries();
468 | // if (dirty.empty())
469 | // return 0;
470 | // lua_createtable(L, dirty.size(), 0);
471 | // lua_Integer i = 1;
472 | // for (auto& s: dirty) {
473 | // lua_pushlstring(L, s.c_str(), s.size());
474 | // lua_seti(L, -2, i++);
475 | // }
476 | // return 1;
477 | //});
478 | ut.set(sol::meta_function::index, evalParm);
479 | sol::stack::push(L, ut);
480 | return 1;
481 | };
482 |
483 | luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
484 | lua_pushcfunction(L, luaopen_parmset);
485 | lua_setfield(L, -2, "ParmSet");
486 | }
487 |
488 | lua_State* ParmSet::defaultLuaRuntime()
489 | {
490 | class LuaRAII {
491 | lua_State* lua_=nullptr;
492 | public:
493 | LuaRAII() {
494 | lua_ = luaL_newstate();
495 | luaL_openlibs(lua_);
496 | }
497 | ~LuaRAII() {
498 | lua_close(lua_);
499 | }
500 | lua_State* lua() const {
501 | return lua_;
502 | }
503 | };
504 | static LuaRAII instance;
505 | return instance.lua();
506 | }
507 |
508 | } // namespace parmscript
509 |
510 |
--------------------------------------------------------------------------------
/parmscript/parmscript.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 |
16 | typedef struct lua_State lua_State;
17 |
18 | namespace parmscript {
19 |
20 | class Parm;
21 | class ParmSet;
22 | using ParmPtr = std::shared_ptr;
23 | using ConstParmPtr = std::shared_ptr;
24 | using ParmSetPtr = std::shared_ptr;
25 | using string=std::string;
26 | template
27 | using hashmap=std::unordered_map;
28 | template
29 | using hashset=std::unordered_set;
30 |
31 | class Parm
32 | {
33 | public:
34 | struct int2 { int x,y; };
35 | struct float2 { float x,y; };
36 | struct float3 { float x,y,z; };
37 | struct float4 { float x,y,z,w; };
38 | struct color { float r,g,b,a; };
39 |
40 | enum class value_type_enum : size_t {
41 | NONE, BOOL, INT, INT2, FLOAT, DOUBLE, FLOAT2, FLOAT3, FLOAT4, COLOR, STRING};
42 | using value_type = std::variant<
43 | std::monostate, bool, int, int2, float, double, float2, float3, float4, color, string>;
44 | enum class ui_type_enum {
45 | FIELD, LABEL, BUTTON, SPACER, SEPARATOR, MENU, GROUP, STRUCT, LIST};
46 |
47 | protected:
48 | ParmSet *root_=nullptr;
49 | ui_type_enum ui_type_=ui_type_enum::LABEL;
50 | value_type_enum expected_value_type_;
51 | value_type value_;
52 | value_type default_;
53 | string name_;
54 | string path_;
55 | string label_;
56 | hashmap meta_;
57 | std::vector menu_values_;
58 | std::vector menu_items_;
59 | std::vector menu_labels_;
60 | // if the scope is a plain struct, then this holds everything
61 | std::vector fields_;
62 | // if the scope is a list, fields_ holds the template (label / default value / everything)
63 | // and listValues_ holds the values.
64 | // e.g., for a list of {string name; int value;} pairs
65 | // fields_[0] == {def of string name}, fields_[1] = {def of int value}
66 | // listValues_[0].fields_[0] = value of first string, i.e., list[0].name
67 | // listValues_[0].fields_[1] = value of first int, i.e., list[0].value
68 | // listValues_[1].fields_[0] = value of second string, i.e., list[1].name
69 | // listValues_[1].fields_[1] = value of second int, i.e., list[1].value
70 | std::vector listValues_;
71 |
72 |
73 | static string titleize(string s)
74 | {
75 | bool space = true;
76 | for (auto& c: s) {
77 | if (std::isspace(c)) {
78 | space = true;
79 | } else if (space) {
80 | c = std::toupper(c);
81 | space = false;
82 | }
83 | }
84 | return s;
85 | }
86 |
87 | public:
88 | Parm(ParmSet* root):root_(root){}
89 | Parm(Parm&&)=default;
90 | ~Parm()=default;
91 | Parm(Parm const& that)
92 | : root_(that.root_)
93 | , ui_type_(that.ui_type_)
94 | , value_(that.value_)
95 | , expected_value_type_(that.expected_value_type_)
96 | , default_(that.default_)
97 | , name_(that.name_)
98 | , path_(that.path_)
99 | , label_(that.label_)
100 | , meta_(that.meta_)
101 | , menu_values_(that.menu_values_)
102 | , menu_items_(that.menu_items_)
103 | , menu_labels_(that.menu_labels_)
104 | {
105 | fields_.reserve(that.fields_.size());
106 | for (auto f: that.fields_)
107 | fields_.push_back(std::make_shared(*f));
108 | listValues_.reserve(that.listValues_.size());
109 | for (auto v: that.listValues_)
110 | listValues_.push_back(std::make_shared(*v));
111 | }
112 |
113 | auto const& name() const { return name_; }
114 | auto const& label() const { return label_; }
115 | auto const& path() const { return path_; }
116 | auto const& value() const { return value_; }
117 | auto const& defaultValue() const { return default_; }
118 | auto const type() const { return expected_value_type_; }
119 | auto const ui() const { return ui_type_; }
120 | auto* root() const { return root_; }
121 | auto const& menuLabels() const { return menu_labels_; }
122 |
123 | // retrieve value:
124 | template
125 | constexpr std::enable_if_t && !std::is_same_v, T>
126 | as() const { return std::get(value_); }
127 |
128 | // get pointer:
129 | template
130 | constexpr auto
131 | getPtr() noexcept { return std::get_if(&value_); }
132 |
133 | // special case for menu:
134 | template
135 | std::enable_if_t, T>
136 | as() const {
137 | if (ui_type_ == ui_type_enum::MENU) {
138 | int idx = std::get(value_);
139 | if (menu_values_.size() == menu_items_.size() && idx>=0 && idx(value_);
146 | }
147 | }
148 | template
149 | std::enable_if_t, T>
150 | as() const {
151 | if (ui_type_ == ui_type_enum::MENU) {
152 | int idx = std::get(value_);
153 | if (idx>=0 && idx(value_);
160 | }
161 | }
162 |
163 | // retrieve value:
164 | template