Compare commits

..

No commits in common. "master" and "windows-port" have entirely different histories.

73 changed files with 277 additions and 1686 deletions

504
LICENSE
View file

@ -1,504 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -1,6 +0,0 @@
The LGPLv2.1 license found in [LICENSE](./LICENSE) also applies retroactively to code committed between the dates of Friday 27 September 2024 to Sunday 22 June 2025 (inclusive), via the commit hashes adfc839098ee12cc180cc00cbb362cb232bfb2a1 and 54e1576eb1065b8f7d3b13c98fc6078620921960
Any forks based on older commits must include a copy of the license file (LICENSE) in addition to this one, provided that the program then complies with
the license terms
Openblocks Copyright (C) 2025 m-doescode / maelstrom071

View file

@ -121,33 +121,6 @@ static void processMethod(CXCursor cur, ClassAnalysis* state) {
state->methods.push_back(anly);
}
static void processOperator(CXCursor cur, ClassAnalysis* state) {
std::optional<std::string> operatorDef = findAnnotation(cur, "OB::def_data_op");
if (!operatorDef) return;
OperatorAnalysis anly;
std::string symbolName = x_clang_toString(clang_getCursorSpelling(cur));
if (!symbolName.starts_with("operator"))
return;
std::string opName = symbolName.substr(8);
// Special case: Unary minus gets its own type
if (clang_Cursor_getNumArguments(cur) == 0)
opName = "-()";
anly.type = opName;
if (clang_Cursor_getNumArguments(cur) != 0) {
CXCursor arg = clang_Cursor_getArgument(cur, 0);
CXType type = clang_getCursorType(arg);
anly.param_type = x_clang_toString(clang_getTypeSpelling(type));
}
state->operators[opName].push_back(anly);
}
// This processes both methods and fields
static void processProperty(CXCursor cur, ClassAnalysis* state) {
std::optional<std::string> propertyDef = findAnnotation(cur, "OB::def_data_prop");
@ -246,7 +219,6 @@ static void processClass(CXCursor cur, AnalysisState* state, std::string classNa
if (kind == CXCursor_CXXMethod) {
processMethod(cur, &anly);
processOperator(cur, &anly);
}
return CXChildVisit_Continue;

View file

@ -19,11 +19,6 @@ struct PropertyAnalysis {
std::string valueType;
};
struct OperatorAnalysis {
std::string type;
std::string param_type;
};
struct MethodParameter {
std::string name;
std::string type;
@ -48,7 +43,6 @@ struct ClassAnalysis {
std::vector<MethodAnalysis> methods;
std::vector<PropertyAnalysis> staticProperties;
std::vector<MethodAnalysis> staticMethods;
std::map<std::string, std::vector<OperatorAnalysis>> operators;
};
struct AnalysisState {

View file

@ -33,17 +33,6 @@ static std::map<std::string, std::string> LUA_PUSH_FUNCS = {
// { "std::string", "lua_pushstring" },
};
static std::map<std::string, std::string> LUA_OP_NAME = {
{ "==", "__eq" },
{ "<", "__lt" },
{ "<=", "__le" },
{ "+", "__add" },
{ "-", "__sub" },
{ "-()", "__unm" },
{ "*", "__mul" },
{ "/", "__div" },
};
static std::string getLuaMethodFqn(std::string className, std::string methodName) {
return "__lua_impl__" + className + "__" + methodName;
}
@ -248,27 +237,14 @@ static void writeLuaMethodImpls(std::ofstream& out, ClassAnalysis& state) {
static void writeLuaValueGenerator(std::ofstream& out, ClassAnalysis& state) {
std::string fqn = state.name;
// Insert additional operators
for (auto& [key, ops] : state.operators) {
std::string opname = LUA_OP_NAME[key];
out << "static int data_" << state.name << opname << "(lua_State*);\n";
}
out << "static int data_" << state.name << "_gc(lua_State*);\n"
"static int data_" << state.name << "_index(lua_State*);\n"
"static int data_" << state.name << "_tostring(lua_State*);\n"
"static const struct luaL_Reg " << state.name << "_metatable [] = {\n"
" {\"__gc\", data_" << state.name << "_gc},\n"
" {\"__index\", data_" << state.name << "_index},\n"
" {\"__tostring\", data_" << state.name << "_tostring},\n";
// Insert additional operators
for (auto& [key, ops] : state.operators) {
std::string opname = LUA_OP_NAME[key];
out << " {\"" + opname + "\", data_" << state.name << opname << "},\n";
}
out << " {NULL, NULL} /* end of array */\n"
" {\"__tostring\", data_" << state.name << "_tostring},\n"
" {NULL, NULL} /* end of array */\n"
"};\n\n";
out << "void " << state.name << "::PushLuaValue(lua_State* L) const {\n"
@ -361,55 +337,6 @@ static void writeLuaValueGenerator(std::ofstream& out, ClassAnalysis& state) {
"}\n\n";
}
static void writeLuaOperatorImpls(std::ofstream& out, ClassAnalysis& state) {
std::string fqn = "" + state.name;
for (auto& [name, ops] : state.operators) {
out << "static int data_" << state.name << LUA_OP_NAME[name] << "(lua_State* L) {\n"
" " << fqn << "* this_ = *(" << fqn << "**)luaL_checkudata(L, 1, \"__mt_" << state.name << "\");\n"
" int n = lua_gettop(L);\n";
out << " ";
// Support multiple overloads of the same function
bool first = true;
for (OperatorAnalysis op : ops) {
if (!first) out << " else ";
first = false;
// Check to see if the arguments possibly match this implementation's parameter types
out << "if (";
// Check number of arguments
out << "n == " << std::to_string(name == "-()" ? 2 : op.param_type == "" ? 1 : 2); // Account for first argument as 'this'
if (op.param_type != "") {
out << " && ";
writeLuaTestArgument(out, op.param_type, 0, true);
}
out << ") {\n"; // End if condition, start if body
if (op.param_type != "") {
writeLuaGetArgument(out, op.param_type, 0, true);
}
if (name == "-()") {
out << " Variant(-*this_).PushLuaValue(L);\n";
} else {
out << " Variant(*this_ " << name << " arg0).PushLuaValue(L);\n";
}
out << " return 1;\n"
" }";
}
// No function implementation matched
out << "\n\n return luaL_error(L, \"Cannot apply '" << name << "' to values of type " << state.name << " and %s \", x_luaL_udatatname(L, 2));\n";
out << "}\n\n"; // End function
}
}
static void writeLuaLibraryGenerator(std::ofstream& out, ClassAnalysis& state) {
std::string fqn = state.name;
@ -524,6 +451,5 @@ void data::writeCodeForClass(std::ofstream& out, std::string headerPath, ClassAn
writeLuaMethodImpls(out, state);
writeLuaValueGenerator(out, state);
writeLuaOperatorImpls(out, state);
writeLuaLibraryGenerator(out, state);
}

View file

@ -15,8 +15,24 @@ Handles editorToolHandles;
std::vector<std::shared_ptr<Instance>> currentSelection;
std::vector<SelectionUpdateHandler> selectionUpdateListeners;
std::vector<PropertyUpdateHandler> propertyUpdatelisteners;
void setSelection(std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer) {
for (SelectionUpdateHandler handler : selectionUpdateListeners) {
handler(currentSelection, newSelection, fromExplorer);
}
currentSelection = newSelection;
}
const std::vector<std::shared_ptr<Instance>> getSelection() {
return currentSelection;
}
void addSelectionListener(SelectionUpdateHandler handler) {
selectionUpdateListeners.push_back(handler);
}
void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue) {
for (PropertyUpdateHandler handler : propertyUpdatelisteners) {

View file

@ -1,7 +1,7 @@
#pragma once
#include "objects/base/instance.h"
#include "handles.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include "objects/datamodel.h"
#include "camera.h"
#include <functional>
@ -11,6 +11,7 @@ class Instance;
// typedef std::function<void(std::shared_ptr<Instance> element, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPreUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPostUpdateHandler;
typedef std::function<void(std::vector<std::shared_ptr<Instance>> oldSelection, std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer)> SelectionUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> instance, std::string property, Variant newValue)> PropertyUpdateHandler;
// TEMPORARY COMMON DATA FOR VARIOUS INTERNAL COMPONENTS
@ -23,5 +24,9 @@ extern std::optional<HierarchyPreUpdateHandler> hierarchyPreUpdateHandler;
extern std::optional<HierarchyPostUpdateHandler> hierarchyPostUpdateHandler;
extern Handles editorToolHandles;
void setSelection(std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer = false);
const std::vector<std::shared_ptr<Instance>> getSelection();
void addSelectionListener(SelectionUpdateHandler handler);
void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
void addPropertyUpdateListener(PropertyUpdateHandler handler);

View file

@ -8,7 +8,6 @@
#define def_data_prop(...) clang::annotate("OB::def_data_prop", #__VA_ARGS__)
#define def_data_method(...) clang::annotate("OB::def_data_method", #__VA_ARGS__)
#define def_data_ctor(...) clang::annotate("OB::def_data_ctor", #__VA_ARGS__)
#define def_data_op(...) clang::annotate("OB::def_data_op", #__VA_ARGS__)
#else
#define def_data(...)
#define def_data_prop(...)

View file

@ -117,10 +117,6 @@ CFrame CFrame::operator -(Vector3 vector) const {
return *this + -vector;
}
bool CFrame::operator ==(CFrame other) const {
return this->Position() == other.Position() && this->rotation == other.rotation;
}
// Serialization
void CFrame::Serialize(pugi::xml_node node) const {

View file

@ -68,10 +68,4 @@ public:
DEF_DATA_OP Vector3 operator *(Vector3) const;
DEF_DATA_OP CFrame operator +(Vector3) const;
DEF_DATA_OP CFrame operator -(Vector3) const;
inline CFrame operator *=(CFrame otherFrame) { return *this = *this * otherFrame; }
inline CFrame operator +=(Vector3 offset) { return *this = *this + offset; }
inline CFrame operator -=(Vector3 offset) { return *this = *this - offset; }
DEF_DATA_OP bool operator ==(CFrame) const;
};

View file

@ -35,10 +35,6 @@ Color3 Color3::FromHex(std::string hex) {
return Color3(r, g, b);
}
bool Color3::operator ==(Color3 other) const {
return this->r == other.r && this->g == other.g && this->b == other.b;
}
// Serialization
void Color3::Serialize(pugi::xml_node node) const {

View file

@ -31,6 +31,4 @@ public:
DEF_DATA_PROP inline float R() const { return r; }
DEF_DATA_PROP inline float G() const { return g; }
DEF_DATA_PROP inline float B() const { return b; }
DEF_DATA_OP bool operator ==(Color3) const;
};

View file

@ -40,18 +40,16 @@ EnumItem Enum::FromValueInternal(int value) const {
return result.value();
}
EnumItem::EnumItem(_EnumData* parentData, std::string name, int value) : parentData(parentData), name(name), value(value) {}
//
std::string Enum::ToString() const {
return "Enum." + this->data->name;
}
bool Enum::operator ==(Enum other) const {
return this->data == other.data;
}
//
EnumItem::EnumItem(_EnumData* parentData, std::string name, int value) : parentData(parentData), name(name), value(value) {}
std::string EnumItem::ToString() const {
return "Enum." + parentData->name + "." + name;
}
@ -71,8 +69,4 @@ result<EnumItem, DataParseError> EnumItem::FromString(std::string string, const
auto result = info.enum_->FromName(string);
if (result.has_value()) return result.value();
return DataParseError(string, "EnumItem");
}
bool EnumItem::operator ==(EnumItem other) const {
return this->parentData == other.parentData && this->value == other.value;
}

View file

@ -31,8 +31,6 @@ public:
EnumItem FromValueInternal(int) const;
DEF_DATA_OP bool operator ==(Enum) const;
std::string ToString() const;
void PushLuaValue(lua_State*) const;
static result<Variant, LuaCastError> FromLuaValue(lua_State*, int);
@ -52,8 +50,6 @@ public:
inline int Value() const { return this->value; }
inline Enum EnumType() const { return Enum(this->parentData); }
DEF_DATA_OP bool operator ==(EnumItem) const;
static result<EnumItem, DataParseError> FromString(std::string, const TypeMeta);
std::string ToString() const;
void Serialize(pugi::xml_node) const;

View file

@ -12,8 +12,8 @@
TypeMeta::TypeMeta(const InstanceType* instType) : descriptor(&InstanceRef::TYPE), instType(instType) {}
InstanceRef::InstanceRef() : ref(nullptr) {};
InstanceRef::InstanceRef(std::weak_ptr<Instance> instance) : ref(instance.expired() ? nullptr : instance.lock()) {};
InstanceRef::InstanceRef() {};
InstanceRef::InstanceRef(std::weak_ptr<Instance> instance) : ref(instance) {};
InstanceRef::~InstanceRef() = default;
const TypeDesc InstanceRef::TYPE = {
@ -27,21 +27,13 @@ const TypeDesc InstanceRef::TYPE = {
};
const std::string InstanceRef::ToString() const {
return ref == nullptr ? "NULL" : ref->name;
}
InstanceRef::operator std::shared_ptr<Instance>() {
return ref;
return ref.expired() ? "" : ref.lock()->name;
}
InstanceRef::operator std::weak_ptr<Instance>() {
return ref;
}
bool InstanceRef::operator ==(InstanceRef other) const {
return this->ref == other.ref;
}
// Serialization
void InstanceRef::Serialize(pugi::xml_node node) const {
@ -58,43 +50,16 @@ static int inst_gc(lua_State*);
static int inst_index(lua_State*);
static int inst_newindex(lua_State*);
static int inst_tostring(lua_State*);
static int inst_eq(lua_State*);
static const struct luaL_Reg metatable [] = {
{"__gc", inst_gc},
{"__index", inst_index},
{"__newindex", inst_newindex},
{"__tostring", inst_tostring},
{"__eq", inst_eq},
{NULL, NULL} /* end of array */
};
void InstanceRef::PushLuaValue(lua_State* L) const {
if (ref == nullptr) return lua_pushnil(L);
// Get or create InstanceRef table
lua_getfield(L, LUA_REGISTRYINDEX, "__instances");
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_newtable(L);
// Set metatable
lua_newtable(L);
lua_pushstring(L, "kv");
lua_setfield(L, -2, "__mode");
lua_setmetatable(L, -2);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, "__instances");
}
// Check if value already exists, and if so, return that instead
lua_pushlightuserdata(L, ref.get());
lua_rawget(L, -2);
if (!lua_isnil(L, -1)) {
lua_remove(L, -2); // Remove __instances
return;
}
lua_pop(L, 1);
if (ref.expired()) return lua_pushnil(L);
int n = lua_gettop(L);
@ -107,13 +72,8 @@ void InstanceRef::PushLuaValue(lua_State* L) const {
// Create the instance's metatable
luaL_newmetatable(L, "__mt_instance");
luaL_register(L, NULL, metatable);
lua_setmetatable(L, n+1);
// Add instance to __instances
lua_pushlightuserdata(L, ref.get());
lua_pushvalue(L, -2); // Push userdata
lua_rawset(L, -4); // Put into __instance
lua_remove(L, -2); // Remove __instance
lua_setmetatable(L, n+1);
}
result<Variant, LuaCastError> InstanceRef::FromLuaValue(lua_State* L, int idx) {
@ -145,7 +105,7 @@ static int inst_index(lua_State* L) {
// Read property
std::optional<PropertyMeta> meta = inst->GetPropertyMeta(key);
if (meta) {
Variant value = inst->GetProperty(key).expect();
Variant value = inst->GetPropertyValue(key).expect();
value.PushLuaValue(L);
return 1;
}
@ -181,7 +141,7 @@ static int inst_newindex(lua_State* L) {
if (value.isError())
return luaL_error(L, "%s", value.errorMessage().value().c_str());
inst->SetProperty(key, value.expect()).expect();
inst->SetPropertyValue(key, value.expect()).expect();
return 0;
}
@ -192,14 +152,4 @@ static int inst_tostring(lua_State* L) {
lua_pushstring(L, inst->name.c_str());
return 1;
}
static int inst_eq(lua_State* L) {
auto userdata = (std::shared_ptr<Instance>**)lua_touserdata(L, 1);
std::shared_ptr<Instance> inst = **userdata;
auto userdata2 = (std::shared_ptr<Instance>**)luaL_checkudata(L, 2, "__mt_instance");
std::shared_ptr<Instance> inst2 = **userdata2;
lua_pushboolean(L, inst == inst2);
return 1;
}
}

View file

@ -2,13 +2,12 @@
#include "base.h"
#include "error/data.h"
#include "utils.h"
#include <memory>
class Instance;
class InstanceRef {
nullable std::shared_ptr<Instance> ref;
std::weak_ptr<Instance> ref;
public:
InstanceRef();
InstanceRef(std::weak_ptr<Instance>);
@ -16,7 +15,6 @@ public:
static const TypeDesc TYPE;
operator std::shared_ptr<Instance>();
operator std::weak_ptr<Instance>();
virtual const std::string ToString() const;
@ -24,6 +22,4 @@ public:
virtual void PushLuaValue(lua_State*) const;
static result<InstanceRef, DataParseError> Deserialize(pugi::xml_node node);
static result<Variant, LuaCastError> FromLuaValue(lua_State*, int idx);
bool operator ==(InstanceRef) const;
};

View file

@ -117,8 +117,6 @@ public:
operator std::weak_ptr<Signal>();
DEF_DATA_OP bool operator ==(SignalRef) const;
virtual const std::string ToString() const;
virtual void Serialize(pugi::xml_node node) const;
virtual void PushLuaValue(lua_State*) const;
@ -136,8 +134,6 @@ public:
operator std::weak_ptr<SignalConnection>();
DEF_DATA_OP bool operator ==(SignalConnectionRef) const;
virtual const std::string ToString() const;
virtual void Serialize(pugi::xml_node node) const;
virtual void PushLuaValue(lua_State*) const;

View file

@ -12,12 +12,12 @@
#include "vector.h"
#include "cframe.h"
// #define __VARIANT_TYPE std::variant< \_
// Null, \_
// Bool, \_
// Int, \_
// Float, \_
// String \_
// #define __VARIANT_TYPE std::variant< \
// Null, \
// Bool, \
// Int, \
// Float, \
// String \
// >
typedef std::variant<

View file

@ -72,18 +72,10 @@ bool Vector3::operator <(Vector3 other) const {
return X() < other.X() && Y() < other.Y() && Z() < other.Z();
}
bool Vector3::operator <=(Vector3 other) const {
return X() <= other.X() && Y() <= other.Y() && Z() <= other.Z();
}
bool Vector3::operator >(Vector3 other) const {
return X() > other.X() && Y() > other.Y() && Z() > other.Z();
}
bool Vector3::operator >=(Vector3 other) const {
return X() >= other.X() && Y() >= other.Y() && Z() >= other.Z();
}
Vector3 Vector3::Cross(Vector3 other) const {
return glm::cross(this->vector, other.vector);
}

View file

@ -55,18 +55,17 @@ public:
DEF_DATA_OP Vector3 operator -() const;
DEF_DATA_OP bool operator <(Vector3) const;
DEF_DATA_OP bool operator <=(Vector3) const;
bool operator >(Vector3) const;
bool operator >=(Vector3) const;
DEF_DATA_OP bool operator >(Vector3) const;
DEF_DATA_OP bool operator ==(Vector3) const;
// Augmented shorthands
inline Vector3 operator *=(float factor) { return *this = *this * factor; }
inline Vector3 operator /=(float factor) { return *this = *this / factor; }
inline Vector3 operator *=(Vector3 factor) { return *this = *this * factor; }
inline Vector3 operator /=(Vector3 factor) { return *this = *this / factor; }
inline Vector3 operator +=(Vector3 vector) { return *this = *this + vector; }
inline Vector3 operator -=(Vector3 vector) { return *this = *this + vector; }
inline Vector3 operator *=(float factor) const { return *this * factor; }
inline Vector3 operator /=(float factor) const { return *this / factor; }
inline Vector3 operator *=(Vector3 factor) const { return *this * factor; }
inline Vector3 operator /=(Vector3 factor) const { return *this / factor; }
inline Vector3 operator +=(Vector3 vector) const { return *this + vector; }
inline Vector3 operator -=(Vector3 vector) const { return *this + vector; }
};
inline void printVec(Vector3 vec) {

View file

@ -3,8 +3,6 @@
#include "datatypes/cframe.h"
#include "datatypes/vector.h"
#include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include <glm/ext/scalar_common.hpp>
#include <memory>
#include <optional>
@ -28,8 +26,7 @@ static rp3d::PhysicsCommon common;
static rp3d::PhysicsWorld* world = common.createPhysicsWorld();
std::shared_ptr<Part> getHandleAdornee() {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (!inst.expired() && inst.lock()->IsA<Part>())
return inst.lock()->CastTo<Part>().expect();
}
@ -80,8 +77,7 @@ Vector3 handleSize(HandleFace face) {
static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, glm::vec3& max) {
int count = 0;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (inst.expired() || !inst.lock()->IsA<Part>()) continue;
std::shared_ptr<Part> part = inst.lock()->CastTo<Part>().expect();
@ -100,8 +96,7 @@ static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, g
}
static std::shared_ptr<Part> getFirstSelectedPart() {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (inst.expired() || !inst.lock()->IsA<Part>()) continue;
return inst.lock()->CastTo<Part>().expect();
@ -111,13 +106,14 @@ static std::shared_ptr<Part> getFirstSelectedPart() {
}
CFrame getLocalHandleCFrame(HandleFace face) {
PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
glm::vec3 _boxPos, boxSize, _boxMin, _boxMax;
int count = getAABBOfSelection(_boxPos, boxSize, _boxMin, _boxMax);
Vector3 size;
if (editorToolHandles.worldMode)
size = assembly.bounds();
if (count == 1 && !editorToolHandles.worldMode)
size = getFirstSelectedPart()->size;
else
size = assembly.size();
size = boxSize;
// Since rotation displays rings, all handles must be the same distance from origin in order for the
// rings to be circular
@ -129,10 +125,12 @@ CFrame getLocalHandleCFrame(HandleFace face) {
}
CFrame getHandleCFrame(HandleFace face) {
PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
glm::vec3 boxPos, boxSize, _boxMin, _boxMax;
int count = getAABBOfSelection(boxPos, boxSize, _boxMin, _boxMax);
if (editorToolHandles.worldMode) {
return getLocalHandleCFrame(face) + assembly.assemblyOrigin().Position();
if (count == 1 && !editorToolHandles.worldMode) {
auto part = getFirstSelectedPart();
return part->cframe * getLocalHandleCFrame(face);
} else
return assembly.assemblyOrigin() * getLocalHandleCFrame(face);
return getLocalHandleCFrame(face) + boxPos;
}

View file

@ -4,16 +4,4 @@ extern "C" {
#include <lauxlib.h>
#include <lualib.h>
#include <lua.h>
}
inline const char* x_luaL_udatatname (lua_State *L, int ud) {
void *p = lua_touserdata(L, ud);
if (p != NULL) {
lua_getmetatable(L, ud);
lua_getfield(L, -1, "__name");
const char* str = lua_tostring(L, -1);
lua_pop(L, 2);
return str;
}
return NULL;
}

View file

@ -182,12 +182,12 @@ void Instance::OnWorkspaceRemoved(std::shared_ptr<Workspace> oldWorkspace) {
// Properties
result<Variant, MemberNotFound> Instance::GetProperty(std::string name) {
result<Variant, MemberNotFound> Instance::GetPropertyValue(std::string name) {
name[0] = toupper(name[0]); // Ignore case of first character
return InternalGetPropertyValue(name);
}
fallible<MemberNotFound, AssignToReadOnlyMember> Instance::SetProperty(std::string name, Variant value, bool sendUpdateEvent) {
fallible<MemberNotFound, AssignToReadOnlyMember> Instance::SetPropertyValue(std::string name, Variant value, bool sendUpdateEvent) {
name[0] = toupper(name[0]); // Ignore case of first character
auto result = InternalSetPropertyValue(name, value);
if (result.isSuccess() && sendUpdateEvent) {
@ -290,7 +290,7 @@ void Instance::Serialize(pugi::xml_node parent, RefStateSerialize state) {
// Update std::shared_ptr<Instance> properties using map above
if (meta.type.descriptor == &InstanceRef::TYPE) {
std::weak_ptr<Instance> refWeak = GetProperty(name).expect("Declared property is missing").get<InstanceRef>();
std::weak_ptr<Instance> refWeak = GetPropertyValue(name).expect("Declared property is missing").get<InstanceRef>();
if (refWeak.expired()) continue;
auto ref = refWeak.lock();
@ -306,7 +306,7 @@ void Instance::Serialize(pugi::xml_node parent, RefStateSerialize state) {
state->refsAwaitingRemap[ref] = refs;
}
} else {
GetProperty(name).expect("Declared property is missing").Serialize(propertyNode);
GetPropertyValue(name).expect("Declared property is missing").Serialize(propertyNode);
}
}
@ -360,14 +360,14 @@ result<std::shared_ptr<Instance>, NoSuchInstance> Instance::Deserialize(pugi::xm
if (remappedRef) {
// If the instance has already been remapped, set the new value
object->SetProperty(propertyName, InstanceRef(remappedRef)).expect();
object->SetPropertyValue(propertyName, InstanceRef(remappedRef)).expect();
} else {
// Otheriise, queue this property to be updated later, and keep its current value
auto& refs = state->refsAwaitingRemap[refId];
refs.push_back(std::make_pair(object, propertyName));
state->refsAwaitingRemap[refId] = refs;
object->SetProperty(propertyName, InstanceRef()).expect();
object->SetPropertyValue(propertyName, InstanceRef()).expect();
}
} else {
auto valueResult = Variant::Deserialize(propertyNode, meta.type);
@ -376,7 +376,7 @@ result<std::shared_ptr<Instance>, NoSuchInstance> Instance::Deserialize(pugi::xm
continue;
}
auto value = valueResult.expect();
object->SetProperty(propertyName, value).expect("Declared property was missing");
object->SetPropertyValue(propertyName, value).expect("Declared property was missing");
}
}
@ -386,7 +386,7 @@ result<std::shared_ptr<Instance>, NoSuchInstance> Instance::Deserialize(pugi::xm
// Remap queued properties
for (std::pair<std::shared_ptr<Instance>, std::string> ref : state->refsAwaitingRemap[remappedId]) {
ref.first->SetProperty(ref.second, InstanceRef(object)).expect();
ref.first->SetPropertyValue(ref.second, InstanceRef(object)).expect();
}
state->refsAwaitingRemap[remappedId].clear();
@ -460,7 +460,7 @@ std::optional<std::shared_ptr<Instance>> Instance::Clone(RefStateClone state) {
// Update std::shared_ptr<Instance> properties using map above
if (meta.type.descriptor == &InstanceRef::TYPE) {
std::weak_ptr<Instance> refWeak = GetProperty(property).expect().get<InstanceRef>();
std::weak_ptr<Instance> refWeak = GetPropertyValue(property).expect().get<InstanceRef>();
if (refWeak.expired()) continue;
auto ref = refWeak.lock();
@ -468,18 +468,18 @@ std::optional<std::shared_ptr<Instance>> Instance::Clone(RefStateClone state) {
if (remappedRef) {
// If the instance has already been remapped, set the new value
newInstance->SetProperty(property, InstanceRef(remappedRef)).expect();
newInstance->SetPropertyValue(property, InstanceRef(remappedRef)).expect();
} else {
// Otheriise, queue this property to be updated later, and keep its current value
auto& refs = state->refsAwaitingRemap[ref];
refs.push_back(std::make_pair(newInstance, property));
state->refsAwaitingRemap[ref] = refs;
newInstance->SetProperty(property, InstanceRef(ref)).expect();
newInstance->SetPropertyValue(property, InstanceRef(ref)).expect();
}
} else {
Variant value = GetProperty(property).expect();
newInstance->SetProperty(property, value).expect();
Variant value = GetPropertyValue(property).expect();
newInstance->SetPropertyValue(property, value).expect();
}
}
@ -488,7 +488,7 @@ std::optional<std::shared_ptr<Instance>> Instance::Clone(RefStateClone state) {
// Remap queued properties
for (std::pair<std::shared_ptr<Instance>, std::string> ref : state->refsAwaitingRemap[shared_from_this()]) {
ref.first->SetProperty(ref.second, InstanceRef(newInstance)).expect();
ref.first->SetPropertyValue(ref.second, InstanceRef(newInstance)).expect();
}
state->refsAwaitingRemap[shared_from_this()].clear();
@ -511,7 +511,7 @@ std::vector<std::pair<std::string, std::shared_ptr<Instance>>> Instance::GetRefe
PropertyMeta meta = GetPropertyMeta(property).expect();
if (meta.type.descriptor != &InstanceRef::TYPE) continue;
std::weak_ptr<Instance> ref = GetProperty(property).expect().get<InstanceRef>();
std::weak_ptr<Instance> ref = GetPropertyValue(property).expect().get<InstanceRef>();
if (ref.expired()) continue;
referenceProperties.push_back(std::make_pair(property, ref.lock()));
}

View file

@ -114,8 +114,8 @@ public:
std::string GetFullName();
// Properties
result<Variant, MemberNotFound> GetProperty(std::string name);
fallible<MemberNotFound, AssignToReadOnlyMember> SetProperty(std::string name, Variant value, bool sendUpdateEvent = true);
result<Variant, MemberNotFound> GetPropertyValue(std::string name);
fallible<MemberNotFound, AssignToReadOnlyMember> SetPropertyValue(std::string name, Variant value, bool sendUpdateEvent = true);
result<PropertyMeta, MemberNotFound> GetPropertyMeta(std::string name);
// Manually trigger the update of a property. Useful internally when setting properties directly
void UpdateProperty(std::string name);

View file

@ -1,12 +1,12 @@
#include "datamodel.h"
#include "objects/base/service.h"
#include "base/service.h"
#include "objects/base/instance.h"
#include "objects/base/refstate.h"
#include "objects/base/service.h"
#include "objects/meta.h"
#include "objects/service/script/serverscriptservice.h"
#include "objects/script/serverscriptservice.h"
#include "datatypes/variant.h"
#include "objects/service/workspace.h"
#include "workspace.h"
#include "logger.h"
#include "panic.h"
#include <pugixml.hpp>
@ -133,7 +133,7 @@ std::shared_ptr<DataModel> DataModel::CloneModel() {
// Update std::shared_ptr<Instance> properties using map above
if (meta.type.descriptor == &InstanceRef::TYPE) {
std::weak_ptr<Instance> refWeak = GetProperty(property).expect().get<InstanceRef>();
std::weak_ptr<Instance> refWeak = GetPropertyValue(property).expect().get<InstanceRef>();
if (refWeak.expired()) continue;
auto ref = refWeak.lock();
@ -141,18 +141,18 @@ std::shared_ptr<DataModel> DataModel::CloneModel() {
if (remappedRef) {
// If the instance has already been remapped, set the new value
newModel->SetProperty(property, InstanceRef(remappedRef)).expect();
newModel->SetPropertyValue(property, InstanceRef(remappedRef)).expect();
} else {
// Otheriise, queue this property to be updated later, and keep its current value
auto& refs = state->refsAwaitingRemap[ref];
refs.push_back(std::make_pair(newModel, property));
state->refsAwaitingRemap[ref] = refs;
newModel->SetProperty(property, InstanceRef(ref)).expect();
newModel->SetPropertyValue(property, InstanceRef(ref)).expect();
}
} else {
Variant value = GetProperty(property).expect();
newModel->SetProperty(property, value).expect();
Variant value = GetPropertyValue(property).expect();
newModel->SetPropertyValue(property, value).expect();
}
}
@ -161,7 +161,7 @@ std::shared_ptr<DataModel> DataModel::CloneModel() {
// Remap queued properties
for (std::pair<std::shared_ptr<Instance>, std::string> ref : state->refsAwaitingRemap[shared_from_this()]) {
ref.first->SetProperty(ref.second, InstanceRef(newModel)).expect();
ref.first->SetPropertyValue(ref.second, InstanceRef(newModel)).expect();
}
// Clone services

View file

@ -3,9 +3,9 @@
#include "datatypes/cframe.h"
#include "datatypes/ref.h"
#include "objects/datamodel.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/part.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include <memory>
#include <reactphysics3d/constraint/FixedJoint.h>
#include <reactphysics3d/engine/PhysicsWorld.h>

View file

@ -1,7 +1,7 @@
#include "rotate.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/part.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include "rendering/renderer.h"
#include <reactphysics3d/constraint/HingeJoint.h>

View file

@ -1,7 +1,7 @@
#include "rotatev.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/part.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include "rendering/renderer.h"
#include <reactphysics3d/constraint/HingeJoint.h>

View file

@ -3,9 +3,9 @@
#include "datatypes/cframe.h"
#include "objects/datamodel.h"
#include "objects/joint/jointinstance.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/part.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include <memory>
#include <reactphysics3d/constraint/FixedJoint.h>
#include <reactphysics3d/engine/PhysicsWorld.h>

View file

@ -3,9 +3,9 @@
#include "datatypes/cframe.h"
#include "objects/datamodel.h"
#include "objects/joint/jointinstance.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/part.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include <memory>
#include <reactphysics3d/constraint/FixedJoint.h>
#include <reactphysics3d/engine/PhysicsWorld.h>

View file

@ -1,6 +1,6 @@
#include "jointsservice.h"
#include "objects/service/workspace.h"
#include "objects/datamodel.h"
#include "workspace.h"
#include "datamodel.h"
#include <memory>
JointsService::JointsService(): Service(&TYPE) {

View file

@ -4,15 +4,14 @@
#include "objects/joint/rotate.h"
#include "objects/joint/rotatev.h"
#include "objects/joint/weld.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/model.h"
#include "objects/part.h"
#include "objects/joint/snap.h"
#include "objects/script.h"
#include "objects/service/script/scriptcontext.h"
#include "objects/service/script/serverscriptservice.h"
#include "objects/service/selection.h"
#include "objects/service/workspace.h"
#include "objects/script/scriptcontext.h"
#include "objects/script/serverscriptservice.h"
#include "objects/workspace.h"
#include "objects/datamodel.h"
std::map<std::string, const InstanceType*> INSTANCE_MAP = {
@ -35,5 +34,4 @@ std::map<std::string, const InstanceType*> INSTANCE_MAP = {
{ "JointsService", &JointsService::TYPE },
{ "ScriptContext", &ScriptContext::TYPE },
{ "ServerScriptService", &ServerScriptService::TYPE },
{ "Selection", &Selection::TYPE },
};

View file

@ -1,4 +1,4 @@
#include "model.h"
Model::Model(): PVInstance(&TYPE) {}
Model::Model(): Instance(&TYPE) {}
Model::~Model() = default;

View file

@ -2,12 +2,11 @@
#include "objects/annotation.h"
#include "objects/base/instance.h"
#include "objects/pvinstance.h"
#include <memory>
// Group object for Parts
class DEF_INST_(explorer_icon="model") Model : public PVInstance {
class DEF_INST_(explorer_icon="model") Model : public Instance {
AUTOGEN_PREAMBLE
public:

View file

@ -9,7 +9,7 @@
#include "objects/joint/rotate.h"
#include "objects/joint/rotatev.h"
#include "objects/joint/weld.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/joint/jointinstance.h"
#include "objects/joint/snap.h"
#include "rendering/renderer.h"
@ -22,7 +22,7 @@
Part::Part(): Part(PartConstructParams { .size = glm::vec3(2, 1.2, 4), .color = Color3(0.639216f, 0.635294f, 0.647059f) }) {
}
Part::Part(PartConstructParams params): PVInstance(&TYPE), cframe(CFrame::FromEulerAnglesXYZ((Vector3)params.rotation) + params.position),
Part::Part(PartConstructParams params): Instance(&TYPE), cframe(CFrame::FromEulerAnglesXYZ((Vector3)params.rotation) + params.position),
size(params.size), color(params.color), anchored(params.anchored), locked(params.locked) {
}
@ -124,6 +124,8 @@ SurfaceType Part::surfaceFromFace(NormalId face) {
}
float Part::GetSurfaceParamA(Vector3 face) {
// printVec(face);
// printf("Enum: %d\n", faceFromNormal(face));
switch (faceFromNormal(face)) {
case Top: return topParamA;
case Bottom: return bottomParamA;

View file

@ -13,7 +13,6 @@
#include <reactphysics3d/reactphysics3d.h>
#include <vector>
#include "annotation.h"
#include "objects/pvinstance.h"
namespace rp = reactphysics3d;
@ -30,7 +29,7 @@ struct PartConstructParams {
class Workspace;
class DEF_INST_(explorer_icon="part") Part : public PVInstance {
class DEF_INST_(explorer_icon="part") Part : public Instance {
AUTOGEN_PREAMBLE
protected:
// Joints where this part is Part0
@ -66,10 +65,10 @@ public:
DEF_PROP_CATEGORY(APPEARANCE)
DEF_PROP Color3 color;
DEF_PROP float transparency = 0.f;
bool selected = false;
DEF_PROP_CATEGORY(BEHAVIOR)
DEF_PROP_(on_update=onUpdated) bool anchored = false;
DEF_PROP_(on_update=onUpdated) bool canCollide = true;
DEF_PROP bool locked = false;
DEF_PROP_CATEGORY(SURFACE)

View file

@ -1,4 +0,0 @@
#include "pvinstance.h"
PVInstance::PVInstance(const InstanceType* type): Instance(type) {}
PVInstance::~PVInstance() = default;

View file

@ -1,13 +0,0 @@
#pragma once
#include "objects/annotation.h"
#include "objects/base/instance.h"
class DEF_INST_ABSTRACT PVInstance : public Instance {
AUTOGEN_PREAMBLE
protected:
PVInstance(const InstanceType*);
public:
~PVInstance();
};

View file

@ -3,8 +3,8 @@
#include "logger.h"
#include "objects/base/instance.h"
#include "objects/base/member.h"
#include "objects/service/script/scriptcontext.h"
#include "objects/service/workspace.h"
#include "objects/script/scriptcontext.h"
#include "objects/workspace.h"
#include "objects/datamodel.h"
#include "datatypes/ref.h"
#include "lua.h" // IWYU pragma: keep

View file

@ -1,6 +1,6 @@
#include "serverscriptservice.h"
#include "objects/script.h"
#include "objects/service/workspace.h"
#include "objects/workspace.h"
#include "objects/datamodel.h"
ServerScriptService::ServerScriptService(): Service(&TYPE) {

View file

@ -1,42 +0,0 @@
#include "selection.h"
#include "objects/datamodel.h"
#include <algorithm>
#include <memory>
Selection::Selection(): Service(&TYPE) {
}
Selection::~Selection() = default;
void Selection::InitService() {
if (initialized) return;
initialized = true;
}
std::vector<std::shared_ptr<Instance>> Selection::Get() {
return selection;
}
void Selection::Set(std::vector<std::shared_ptr<Instance>> newSelection) {
selection = newSelection;
SelectionChanged->Fire();
}
void Selection::Add(std::vector<std::shared_ptr<Instance>> instances) {
for (auto inst : instances) {
if (std::find(selection.begin(), selection.end(), inst) == selection.end()) {
selection.push_back(inst);
}
}
SelectionChanged->Fire();
}
void Selection::Remove(std::vector<std::shared_ptr<Instance>> instances) {
for (auto inst : instances) {
std::vector<std::shared_ptr<Instance>>::iterator p;
if ((p = std::find(selection.begin(), selection.end(), inst)) != selection.end()) {
selection.erase(p);
}
}
SelectionChanged->Fire();
}

View file

@ -1,28 +0,0 @@
#pragma once
#include "datatypes/signal.h"
#include "objects/annotation.h"
#include "objects/base/service.h"
#include <memory>
#include <vector>
class DEF_INST_SERVICE Selection : public Service {
AUTOGEN_PREAMBLE
private:
std::vector<std::shared_ptr<Instance>> selection;
protected:
void InitService() override;
bool initialized = false;
public:
Selection();
~Selection();
static inline std::shared_ptr<Instance> Create() { return std::make_shared<Selection>(); };
std::vector<std::shared_ptr<Instance>> Get();
void Set(std::vector<std::shared_ptr<Instance>> newSelection);
void Add(std::vector<std::shared_ptr<Instance>> instances);
void Remove(std::vector<std::shared_ptr<Instance>> instances);
SignalSource SelectionChanged;
};

View file

@ -3,13 +3,12 @@
#include "datatypes/ref.h"
#include "datatypes/vector.h"
#include "objects/base/instance.h"
#include "objects/service/jointsservice.h"
#include "objects/jointsservice.h"
#include "objects/joint/jointinstance.h"
#include "objects/datamodel.h"
#include "physics/util.h"
#include <memory>
#include <reactphysics3d/collision/CollisionCallback.h>
#include <reactphysics3d/collision/OverlapCallback.h>
#include <reactphysics3d/engine/PhysicsCommon.h>
rp::PhysicsCommon* Workspace::physicsCommon = new rp::PhysicsCommon;
@ -43,25 +42,6 @@ void PhysicsEventListener::onContact(const rp::CollisionCallback::CallbackData&
}
}
void PhysicsEventListener::onTrigger(const rp::OverlapCallback::CallbackData& data) {
for (size_t i = 0; i < data.getNbOverlappingPairs(); i++) {
auto pair = data.getOverlappingPair(i);
auto type = pair.getEventType();
if (type == rp::OverlapCallback::OverlapPair::EventType::OverlapStay) continue;
auto part0 = reinterpret_cast<Part*>(pair.getBody1()->getUserData())->shared<Part>();
auto part1 = reinterpret_cast<Part*>(pair.getBody2()->getUserData())->shared<Part>();
if (type == reactphysics3d::OverlapCallback::OverlapPair::EventType::OverlapStart) {
part0->Touched->Fire({ (Variant)InstanceRef(part1) });
part1->Touched->Fire({ (Variant)InstanceRef(part0) });
} else if (type == reactphysics3d::OverlapCallback::OverlapPair::EventType::OverlapExit) {
part0->TouchEnded->Fire({ (Variant)InstanceRef(part1) });
part1->TouchEnded->Fire({ (Variant)InstanceRef(part0) });
}
}
}
void Workspace::InitService() {
if (initialized) return;
initialized = true;
@ -127,9 +107,6 @@ void Workspace::SyncPartPhysics(std::shared_ptr<Part> part) {
part->rigidBody->setType(part->anchored ? rp::BodyType::STATIC : rp::BodyType::DYNAMIC);
part->rigidBody->getCollider(0)->setCollisionCategoryBits(0b11);
part->rigidBody->getCollider(0)->setIsSimulationCollider(part->canCollide);
part->rigidBody->getCollider(0)->setIsTrigger(!part->canCollide);
rp::Material& material = part->rigidBody->getCollider(0)->getMaterial();
material.setFrictionCoefficient(0.35);
material.setMassDensity(1.f);

View file

@ -44,7 +44,6 @@ class PhysicsEventListener : public rp::EventListener {
PhysicsEventListener(Workspace*);
void onContact(const rp::CollisionCallback::CallbackData&) override;
void onTrigger(const rp::OverlapCallback::CallbackData&) override;
};
class DEF_INST_SERVICE_(explorer_icon="workspace") Workspace : public Service {

View file

@ -6,7 +6,6 @@
#include "math_helper.h"
#include "objects/base/instance.h"
#include "objects/part.h"
#include "objects/service/selection.h"
#include <glm/common.hpp>
#include <memory>
#include <vector>
@ -15,8 +14,7 @@ PartAssembly::PartAssembly(std::vector<std::shared_ptr<Part>> parts, bool worldM
if (parts.size() == 0) return;
if (parts.size() == 1 && !worldMode) {
_assemblyOrigin = parts[0]->cframe;
_size = parts[0]->size;
_bounds = parts[0]->GetAABB();
_bounds = parts[0]->size;
return;
}
@ -32,39 +30,21 @@ PartAssembly::PartAssembly(std::vector<std::shared_ptr<Part>> parts, bool worldM
getAABBCoords(pos, size, min, max);
_assemblyOrigin = CFrame() + pos;
_size = _bounds = size;
_bounds = size;
}
PartAssembly PartAssembly::FromSelection(std::vector<std::shared_ptr<Instance>> newSelection) {
std::vector<std::shared_ptr<Part>> selection;
for (std::shared_ptr<Instance> obj : newSelection) {
if (!obj->IsA<PVInstance>()) continue;
for (std::weak_ptr<Instance> obj : newSelection) {
if (obj.expired() || !obj.lock()->IsA<Part>()) continue;
if (obj->IsA<Part>())
selection.push_back(obj->CastTo<Part>().expect());
// Add object descendants
for (DescendantsIterator it = obj->GetDescendantsStart(); it != obj->GetDescendantsEnd(); it++) {
if (!(*it)->IsA<Part>()) continue;
selection.push_back((*it)->CastTo<Part>().expect());
}
selection.push_back(obj.lock()->CastTo<Part>().expect());
}
return PartAssembly(selection, editorToolHandles.worldMode);
}
PartAssembly PartAssembly::FromSelection(std::shared_ptr<Selection> selection) {
return FromSelection(selection->Get());
}
void PartAssembly::SetCollisionsEnabled(bool enabled) {
for (auto part : parts) {
part->rigidBody->getCollider(0)->setIsWorldQueryCollider(enabled);
}
}
void PartAssembly::SetOrigin(CFrame newOrigin) {
for (auto part : parts) {
part->cframe = newOrigin * (_assemblyOrigin.Inverse() * part->cframe);
@ -117,18 +97,4 @@ void PartAssembly::Scale(Vector3 newSize, bool scaleUp) {
}
_bounds = _bounds * factor;
}
std::vector<PartTransformState> PartAssembly::GetCurrentTransforms() {
std::vector<PartTransformState> transforms;
for (auto part : parts) {
PartTransformState t;
t.part = part;
t.cframe = part->cframe;
t.size = part->size;
transforms.push_back(t);
}
return transforms;
}

View file

@ -6,33 +6,21 @@
class Part;
class Instance;
class Selection;
struct PartTransformState {
std::shared_ptr<Part> part;
Vector3 size;
CFrame cframe;
};
const std::vector<std::shared_ptr<Instance>> getSelection();
class PartAssembly {
CFrame _assemblyOrigin;
Vector3 _bounds;
Vector3 _size;
std::vector<std::shared_ptr<Part>> parts;
public:
PartAssembly(std::vector<std::shared_ptr<Part>>, bool worldMode = false);
static PartAssembly FromSelection(std::vector<std::shared_ptr<Instance>> selection);
static PartAssembly FromSelection(std::shared_ptr<Selection> selection);
static PartAssembly FromSelection(std::vector<std::shared_ptr<Instance>> selection = getSelection());
inline CFrame assemblyOrigin() { return _assemblyOrigin; };
inline Vector3 bounds() { return _bounds; };
inline Vector3 size() { return _size; };
inline bool multipleSelected() { return parts.size() > 1; }
// Gets the current transform state of all the parts in the assembly
std::vector<PartTransformState> GetCurrentTransforms();
// Transforms the assembly such that newOrigin is now this assembly's new assemblyOrigin
void SetOrigin(CFrame newOrigin);
@ -44,8 +32,4 @@ public:
// If multiple parts are selected, finds the greatest scale factor of each component pair, and
// scales it up by that amount
void Scale(Vector3 newSize, bool scaleUp = true);
// Update temporary collisions of rigidbodies. Useful for ignoring
// items for raycasts
void SetCollisionsEnabled(bool enabled);
};

View file

@ -19,7 +19,6 @@
#include "datatypes/vector.h"
#include "handles.h"
#include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include "rendering/torus.h"
#include "shader.h"
@ -271,8 +270,8 @@ static CFrame XYZToZXY(glm::vec3(0, 0, 0), -glm::vec3(1, 0, 0), glm::vec3(0, 0,
void renderHandles() {
if (!editorToolHandles.active) return;
auto assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (assembly.size() == Vector3::ZERO) return;
auto assembly = PartAssembly::FromSelection();
if (assembly.bounds() == Vector3::ZERO) return;
glDepthMask(GL_TRUE);
glCullFace(GL_BACK);
@ -449,12 +448,15 @@ void renderOutlines() {
glm::vec3 min, max;
bool first = true;
int count = 0;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto inst : selection->Get()) {
for (auto it = gWorkspace()->GetDescendantsStart(); it != gWorkspace()->GetDescendantsEnd(); it++) {
std::shared_ptr<Instance> inst = *it;
if (inst->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst);
if (!part->selected) continue;
count++;
if (first)
min = part->position(), max = part->position();
first = false;
@ -473,10 +475,11 @@ void renderOutlines() {
}
// Render AABB of selected parts
PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (selectionAssembly.size() == Vector3()) return;
glm::vec3 outlineSize = selectionAssembly.bounds();
glm::vec3 outlinePos = selectionAssembly.assemblyOrigin().Position();
if (count <= 1) return;
glm::vec3 outlineSize, outlinePos;
outlineSize = (max - min);
outlinePos = (max + min) / 2.f;
glm::mat4 model = glm::translate(glm::mat4(1.0f), outlinePos);
model = glm::scale(model, outlineSize + glm::vec3(0.1));
@ -496,7 +499,7 @@ void renderSelectionAssembly() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
PartAssembly selectionAssembly = PartAssembly::FromSelection();
// Use shader
outlineShader->use();
@ -514,9 +517,9 @@ void renderSelectionAssembly() {
outlineShader->set("color", glm::vec3(1.f, 0.f, 0.f));
glm::mat4 model = selectionAssembly.assemblyOrigin();
model = glm::scale(model, (glm::vec3)selectionAssembly.size() + glm::vec3(0.1));
model = glm::scale(model, (glm::vec3)selectionAssembly.bounds() + glm::vec3(0.1));
outlineShader->set("model", model);
outlineShader->set("scale", (glm::vec3)selectionAssembly.size() + glm::vec3(0.05));
outlineShader->set("scale", (glm::vec3)selectionAssembly.bounds() + glm::vec3(0.05));
outlineShader->set("thickness", 0.2f);
OUTLINE_MESH->bind();
@ -553,14 +556,14 @@ void renderRotationArcs() {
// Pass in the camera position
handleShader->set("viewPos", camera.cameraPos);
PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
PartAssembly assembly = PartAssembly::FromSelection();
for (HandleFace face : HandleFace::Faces) {
if (glm::any(glm::lessThan(face.normal, glm::vec3(0)))) continue;
glm::mat4 model = assembly.assemblyOrigin() * CFrame(glm::vec3(0), face.normal, glm::vec3(0, 1.01, 0.1));
handleShader->set("model", model);
float radius = glm::max(assembly.size().X(), assembly.size().Y(), assembly.size().Z()) / 2.f + 2.f;
float radius = glm::max(assembly.bounds().X(), assembly.bounds().Y(), assembly.bounds().Z()) / 2.f + 2.f;
handleShader->set("material", Material {
.diffuse = glm::abs(face.normal),

View file

@ -1,10 +0,0 @@
#pragma once
#ifdef __clang__
#pragma clang diagnostic ignored "-Wnullability-extension"
#define nullable _Nullable
#define notnull _Nonnull
#else
#define nullable
#define notnull
#endif

View file

@ -26,8 +26,6 @@ set(PROJECT_SOURCES
mainglwidget.cpp
placedocument.h
placedocument.cpp
undohistory.h
undohistory.cpp
panes/explorerview.h
panes/explorerview.cpp
panes/explorermodel.h
@ -38,10 +36,6 @@ set(PROJECT_SOURCES
panes/outputtextview.cpp
script/scriptdocument.h
script/scriptdocument.cpp
aboutdialog.ui
aboutdialog.h
aboutdialog.cpp
editor.qrc
${TS_FILES}
)

View file

@ -1 +0,0 @@
../LICENSE

View file

@ -1,45 +0,0 @@
#include "aboutdialog.h"
#include "./ui_aboutdialog.h"
#include <qdialogbuttonbox.h>
#include <qnamespace.h>
#include <qplaintextedit.h>
class LicenseDialog : public QDialog {
public:
LicenseDialog(QWidget* parent = nullptr) : QDialog(parent) {
this->resize(700, 500);
this->setMinimumSize(QSize(500, 500));
this->setMaximumSize(QSize(500, 500));
setWindowTitle("License");
QFile licenseFile(":/LICENSE");
licenseFile.open(QFile::ReadOnly);
QString licenseContent = licenseFile.readAll();
licenseFile.close();
QPlainTextEdit* licenseText = new QPlainTextEdit(this);
licenseText->setGeometry(QRect(10, 10, 500-20, 500-20-32-10));
licenseText->setPlainText(licenseContent);
QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setGeometry(QRect(10, 500-32-10, 500-20, 32));
buttonBox->setOrientation(Qt::Orientation::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::StandardButton::Close);
QObject::connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
};
};
AboutDialog::AboutDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::AboutDialog)
{
ui->setupUi(this);
connect(ui->viewLicense, &QLabel::linkActivated, [this]() {
(new LicenseDialog(this))->open();
});
}

View file

@ -1,23 +0,0 @@
#pragma once
#include <qdialog.h>
#include <qobjectdefs.h>
QT_BEGIN_NAMESPACE
namespace Ui {
class AboutDialog;
}
QT_END_NAMESPACE
class AboutDialog : public QDialog
{
Q_OBJECT
Ui::AboutDialog *ui;
public:
AboutDialog(QWidget *parent = nullptr);
~AboutDialog() = default;
protected:
void linkActivated(const QString &link);
};

View file

@ -1,137 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AboutDialog</class>
<widget class="QDialog" name="AboutDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>582</width>
<height>162</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>582</width>
<height>162</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>582</width>
<height>162</height>
</size>
</property>
<property name="windowTitle">
<string>About Openblocks</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>220</x>
<y>110</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Orientation::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::StandardButton::Close</set>
</property>
</widget>
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>20</x>
<y>10</y>
<width>81</width>
<height>81</height>
</rect>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="editor.qrc">:/placeholder-logo.png</pixmap>
</property>
</widget>
<widget class="QLabel" name="label_2">
<property name="geometry">
<rect>
<x>110</x>
<y>20</y>
<width>261</width>
<height>21</height>
</rect>
</property>
<property name="text">
<string>Openblocks Engine ALPHA SNAPSHOT</string>
</property>
</widget>
<widget class="QLabel" name="label_3">
<property name="geometry">
<rect>
<x>110</x>
<y>50</y>
<width>471</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>Copright 2025 GNU Lesser General Public License v2.1</string>
</property>
</widget>
<widget class="QLabel" name="viewLicense">
<property name="geometry">
<rect>
<x>110</x>
<y>80</y>
<width>191</width>
<height>18</height>
</rect>
</property>
<property name="text">
<string>&lt;a href=&quot;/license&quot;&gt;View license...&lt;/a&gt;</string>
</property>
</widget>
</widget>
<resources>
<include location="editor.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>AboutDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>AboutDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View file

@ -1,6 +0,0 @@
<RCC>
<qresource>
<file>placeholder-logo.png</file>
<file>LICENSE</file>
</qresource>
</RCC>

View file

@ -1,3 +1,4 @@
#include "error/data.h"
#include "mainwindow.h"
#include "logger.h"

View file

@ -1,7 +1,6 @@
#include <GL/glew.h>
#include <glm/common.hpp>
#include <glm/vector_relational.hpp>
#include <memory>
#include <qnamespace.h>
#include <qsoundeffect.h>
#include <string>
@ -14,14 +13,11 @@
#include "common.h"
#include "math_helper.h"
#include "objects/base/instance.h"
#include "objects/pvinstance.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include "physics/util.h"
#include "rendering/renderer.h"
#include "rendering/shader.h"
#include "datatypes/variant.h"
#include "undohistory.h"
#define PI 3.14159
#define M_mainWindow dynamic_cast<MainWindow*>(window())
@ -121,8 +117,6 @@ CFrame snapCFrame(CFrame frame) {
return CFrame(frame.Position(), frame.Position() + closestVec1, closestVec2);
}
std::vector<PartTransformState> initialTransforms;
bool tryMouseContextMenu = false;
bool isMouseDragging = false;
std::weak_ptr<Part> draggingObject;
@ -136,10 +130,10 @@ void MainGLWidget::handleObjectDrag(QMouseEvent* evt) {
QPoint position = evt->pos();
initialAssembly.SetCollisionsEnabled(false);
glm::vec3 pointDir = camera.getScreenDirection(glm::vec2(position.x(), position.y()), glm::vec2(width(), height()));
std::optional<const RaycastResult> rayHit = gWorkspace()->CastRayNearest(camera.cameraPos, pointDir, 50000);
initialAssembly.SetCollisionsEnabled(true);
std::optional<const RaycastResult> rayHit = gWorkspace()->CastRayNearest(camera.cameraPos, pointDir, 50000, [](std::shared_ptr<Part> part) {
return (part == draggingObject.lock()) ? FilterResult::PASS : FilterResult::TARGET;
});
if (!rayHit) return;
@ -152,13 +146,13 @@ void MainGLWidget::handleObjectDrag(QMouseEvent* evt) {
Vector3 vec = rayHit->worldPoint + (tFormedInitialPos - tFormedHitPos);
// The part being dragged's frame local to the hit target's frame, but without its position component
// To find a world vector local to the new frame, use newFrame, not localFrame, as localFrame is localFrame is local to targetFrame in itself
CFrame localFrame = (targetFrame.Inverse() * (initialAssembly.assemblyOrigin().Rotation() + vec));
CFrame localFrame = (targetFrame.Inverse() * (draggingObject.lock()->cframe.Rotation() + vec));
// Snap axis
localFrame = snapCFrame(localFrame);
// Snap to studs
Vector3 draggingPartSize = initialAssembly.size();
Vector3 draggingPartSize = draggingObject.lock()->size;
glm::vec3 inverseNormalPartSize = (Vector3)(partSize - glm::vec3(localFrame.Rotation() * draggingPartSize)) * inverseSurfaceNormal / 2.f;
if (snappingFactor() > 0)
localFrame = localFrame.Rotation() + glm::round(glm::vec3(localFrame.Position() * inverseSurfaceNormal - inverseNormalPartSize) / snappingFactor()) * snappingFactor() + inverseNormalPartSize
@ -168,9 +162,14 @@ void MainGLWidget::handleObjectDrag(QMouseEvent* evt) {
// Unsink the object
// Get the normal of the surface relative to the part's frame, and get the size along that vector
Vector3 unsinkOffset = newFrame.Rotation() * ((newFrame.Rotation().Inverse() * rayHit->worldNormal) * initialAssembly.size() / 2);
Vector3 unsinkOffset = newFrame.Rotation() * ((newFrame.Rotation().Inverse() * rayHit->worldNormal) * draggingObject.lock()->size / 2);
initialAssembly.SetOrigin(newFrame + unsinkOffset);
draggingObject.lock()->cframe = newFrame + unsinkOffset;
gWorkspace()->SyncPartPhysics(draggingObject.lock());
draggingObject.lock()->UpdateProperty("Position");
sendPropertyUpdatedSignal(draggingObject.lock(), "Position", draggingObject.lock()->position());
}
inline glm::vec3 vec3fy(glm::vec4 vec) {
@ -184,7 +183,7 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
QPoint position = evt->pos();
// auto part = getHandleAdornee();
auto part = getHandleAdornee();
// This was actually quite a difficult problem to solve, managing to get the handle to go underneath the cursor
@ -196,7 +195,7 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
CFrame handleCFrame = getHandleCFrame(draggingHandle.value()) + dragStartHandleOffset;
// Current frame. Identity frame if worldMode == true, selected object's frame if worldMode == false
CFrame frame = editorToolHandles.worldMode ? CFrame::IDENTITY + initialAssembly.assemblyOrigin().Position() : initialAssembly.assemblyOrigin().Rotation();
CFrame frame = editorToolHandles.worldMode ? CFrame::IDENTITY + part->position() : part->cframe.Rotation();
// Segment from axis stretching -4096 to +4096 rel to handle's position
glm::vec3 axisSegment0 = handleCFrame.Position() + (-handleCFrame.LookVector() * 4096.0f);
@ -221,24 +220,24 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
absDiff = handleCFrame.Rotation() * Vector3(0, 0, diff);
}
PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
PartAssembly selectionAssembly = PartAssembly::FromSelection();
if (editorToolHandles.handlesType == MoveHandles) {
selectionAssembly.TransformBy(CFrame() + absDiff);
} else if (editorToolHandles.handlesType == ScaleHandles) {
if (evt->modifiers() & Qt::AltModifier) {
// If size gets too small, don't
if (glm::any(glm::lessThan(glm::vec3(selectionAssembly.size() + abs(draggingHandle->normal) * diff * 2.f), glm::vec3(0.001f))))
if (glm::any(glm::lessThan(glm::vec3(selectionAssembly.bounds() + abs(draggingHandle->normal) * diff * 2.f), glm::vec3(0.001f))))
return;
selectionAssembly.Scale(selectionAssembly.size() + abs(draggingHandle->normal) * diff * 2.f, diff > 0);
selectionAssembly.Scale(selectionAssembly.bounds() + abs(draggingHandle->normal) * diff * 2.f, diff > 0);
} else {
// If size gets too small, don't
if (glm::any(glm::lessThan(glm::vec3(selectionAssembly.size() + abs(draggingHandle->normal) * diff), glm::vec3(0.001f))))
if (glm::any(glm::lessThan(glm::vec3(selectionAssembly.bounds() + abs(draggingHandle->normal) * diff), glm::vec3(0.001f))))
return;
selectionAssembly.TransformBy(CFrame() + absDiff * 0.5f);
selectionAssembly.Scale(selectionAssembly.size() + abs(draggingHandle->normal) * diff, diff > 0);
selectionAssembly.Scale(selectionAssembly.bounds() + abs(draggingHandle->normal) * diff, diff > 0);
}
}
}
@ -362,7 +361,6 @@ void MainGLWidget::mouseMoveEvent(QMouseEvent* evt) {
}
void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
initialTransforms = {};
tryMouseContextMenu = evt->button() == Qt::RightButton;
switch(evt->button()) {
// Camera drag
@ -379,9 +377,8 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
auto handle = raycastHandle(pointDir);
if (handle.has_value()) {
startPoint = glm::vec2(evt->pos().x(), evt->pos().y());
initialAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
initialAssembly = PartAssembly::FromSelection();
initialFrame = initialAssembly.assemblyOrigin();
initialTransforms = PartAssembly::FromSelection(gDataModel->GetService<Selection>()).GetCurrentTransforms();
isMouseDragging = true;
draggingHandle = handle;
startLinearTransform(evt);
@ -389,24 +386,11 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
}
// raycast part
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::optional<const RaycastResult> rayHit = gWorkspace()->CastRayNearest(camera.cameraPos, pointDir, 50000);
if (!rayHit || !partFromBody(rayHit->body)) { selection->Set({}); return; }
if (!rayHit || !partFromBody(rayHit->body)) { setSelection({}); return; }
std::shared_ptr<Part> part = partFromBody(rayHit->body);
if (part->locked) { selection->Set({}); return; }
std::shared_ptr<PVInstance> selObject = part;
// Traverse to the root model
if (~evt->modifiers() & Qt::AltModifier) {
std::optional<std::shared_ptr<Instance>> nextParent = selObject->GetParent();
while (nextParent.value() && nextParent.value()->IsA("Model")) {
selObject = std::dynamic_pointer_cast<PVInstance>(nextParent.value()); nextParent = selObject->GetParent();
}
}
initialAssembly = PartAssembly::FromSelection({selObject});
initialFrame = initialAssembly.assemblyOrigin();
if (part->locked) { setSelection({}); return; }
initialFrame = part->cframe;
initialHitPos = rayHit->worldPoint;
initialHitNormal = rayHit->worldNormal;
@ -435,16 +419,20 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
//part.selected = true;
isMouseDragging = true;
draggingObject = part;
initialTransforms = PartAssembly::FromSelection({part}).GetCurrentTransforms();
if (evt->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier)) {
auto sel = selection->Get();
if (std::find(sel.begin(), sel.end(), selObject) == sel.end())
selection->Add({ selObject });
else
selection->Remove({ selObject });
} else {
selection->Set({ selObject });
}
if (evt->modifiers() & Qt::ControlModifier) {
std::vector<std::shared_ptr<Instance>> currentSelection = getSelection();
for (size_t i = 0; i < currentSelection.size(); i++) {
std::shared_ptr<Instance> inst = currentSelection[i];
if (inst == part) {
currentSelection.erase(currentSelection.begin() + i);
goto skipAddPart;
}
}
currentSelection.push_back(part);
skipAddPart:
setSelection(currentSelection);
} else
setSelection({ part });
// Disable bit so that we can ignore the part while raycasting
// part->rigidBody->getCollider(0)->setCollisionCategoryBits(0b10);
@ -461,17 +449,6 @@ void MainGLWidget::mouseReleaseEvent(QMouseEvent* evt) {
draggingObject = {};
draggingHandle = std::nullopt;
if (!initialTransforms.empty()) {
UndoState historyState;
for (auto t : initialTransforms) {
historyState.push_back(UndoStatePropertyChanged { t.part, "CFrame", t.cframe, t.part->cframe });
historyState.push_back(UndoStatePropertyChanged { t.part, "Size", t.size, t.part->size });
}
M_mainWindow->undoManager.PushState(historyState);
}
// Open context menu
if (tryMouseContextMenu)
contextMenu.exec(QCursor::pos());
@ -522,8 +499,20 @@ void MainGLWidget::keyPressEvent(QKeyEvent* evt) {
}));
gWorkspace()->SyncPartPhysics(lastPart);
lastPart->name = "Part" + std::to_string(partId++);
M_mainWindow->undoManager.PushState({ UndoStateInstanceCreated { lastPart, gWorkspace() } });
}
if (evt->key() == Qt::Key_U)
Logger::info("info message");
if (evt->key() == Qt::Key_I)
Logger::warning("warning message");
if (evt->key() == Qt::Key_O)
Logger::error("error message");
if (evt->key() == Qt::Key_C && getSelection().size() > 0)
getSelection()[0]->Clone().value()->SetParent(gWorkspace());
if (evt->key() == Qt::Key_H && getSelection().size() > 0)
Logger::infof("Object at: 0x%x\n", getSelection()[0].get());
}
void MainGLWidget::keyReleaseEvent(QKeyEvent* evt) {

View file

@ -1,23 +1,19 @@
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "common.h"
#include "aboutdialog.h"
#include "logger.h"
#include "objects/datamodel.h"
#include "objects/model.h"
#include "objects/service/selection.h"
#include "placedocument.h"
#include "script/scriptdocument.h"
#include "undohistory.h"
#include <cstdio>
#include <memory>
#include <qclipboard.h>
#include <qevent.h>
#include <qglobal.h>
#include <qkeysequence.h>
#include <qmessagebox.h>
#include <qmimedata.h>
#include <qnamespace.h>
#include <qsoundeffect.h>
#include <qstylefactory.h>
#include <qstylehints.h>
#include <qmdisubwindow.h>
@ -47,6 +43,15 @@ inline bool isDarkMode() {
QtMessageHandler defaultMessageHandler = nullptr;
// std::map<QtMsgType, Logger::LogLevel> QT_MESSAGE_TYPE_TO_LOG_LEVEL = {
// { QtMsgType::QtInfoMsg, Logger::LogLevel::INFO },
// { QtMsgType::QtSystemMsg, Logger::LogLevel::INFO },
// { QtMsgType::QtDebugMsg, Logger::LogLevel::DEBUG },
// { QtMsgType::QtWarningMsg, Logger::LogLevel::WARNING },
// { QtMsgType::QtCriticalMsg, Logger::LogLevel::ERROR },
// { QtMsgType::QtFatalMsg, Logger::LogLevel::FATAL_ERROR },
// };
void logQtMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
// Logger::log("[Qt] " + msg.toStdString(), QT_MESSAGE_TYPE_TO_LOG_LEVEL[type]);
Logger::LogLevel logLevel = type == QtMsgType::QtFatalMsg ? Logger::LogLevel::FATAL_ERROR : Logger::LogLevel::DEBUG;
@ -55,13 +60,6 @@ void logQtMessage(QtMsgType type, const QMessageLogContext &context, const QStri
// if (defaultMessageHandler) defaultMessageHandler(type, context, msg);
}
inline void playSound(QString path) {
QSoundEffect *sound = new QSoundEffect;
sound->setSource(QUrl::fromLocalFile(path));
sound->play();
sound->connect(sound, &QSoundEffect::playingChanged, [=]() { /* Thank you QSound source code! */ sound->deleteLater(); return false; });
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
@ -71,8 +69,6 @@ MainWindow::MainWindow(QWidget *parent)
ui->setupUi(this);
setMouseTracking(true);
ui->actionRedo->setShortcuts({QKeySequence("Ctrl+Shift+Z"), QKeySequence("Ctrl+Y")});
QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() + QStringList { "./assets/icons" });
if (isDarkMode())
QIcon::setFallbackThemeName("editor-dark");
@ -93,6 +89,28 @@ MainWindow::MainWindow(QWidget *parent)
connectActionHandlers();
// Update properties
addSelectionListener([&](auto oldSelection, auto newSelection, bool fromExplorer) {
if (newSelection.size() == 0) return;
if (newSelection.size() > 1)
ui->propertiesView->setSelected(std::nullopt);
ui->propertiesView->setSelected(newSelection[0]);
});
addSelectionListener([&](auto oldSelection, auto newSelection, bool __) {
for (std::weak_ptr<Instance> inst : oldSelection) {
if (inst.expired() || inst.lock()->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst.lock());
part->selected = false;
}
for (std::weak_ptr<Instance> inst : newSelection) {
if (inst.expired() || inst.lock()->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst.lock());
part->selected = true;
}
});
// ui->explorerView->Init(ui);
placeDocument = new PlaceDocument(this);
placeDocument->setAttribute(Qt::WA_DeleteOnClose, true);
@ -100,17 +118,8 @@ MainWindow::MainWindow(QWidget *parent)
ui->mdiArea->currentSubWindow()->showMaximized();
ui->mdiArea->findChild<QTabBar*>()->setExpanding(false);
placeDocument->init();
ui->propertiesView->init();
ui->mdiArea->setTabsClosable(true);
// Undo/Redo
ui->actionUndo->setEnabled(false);
ui->actionRedo->setEnabled(false);
undoManager.SetUndoStateListener([&]() {
updateToolbars();
});
}
void MainWindow::closeEvent(QCloseEvent* evt) {
@ -126,10 +135,9 @@ void MainWindow::closeEvent(QCloseEvent* evt) {
if (result == QMessageBox::Cancel) return evt->ignore();
if (result == QMessageBox::Save) {
std::optional<std::string> path;
if (!gDataModel->HasFile()) {
if (!gDataModel->HasFile())
path = openFileDialog("Openblocks Level (*.obl)", ".obl", QFileDialog::AcceptSave, QString::fromStdString("Save " + gDataModel->name));
if (!path || path == "") return evt->ignore();
}
if (!path || path == "") return evt->ignore();
gDataModel->SaveToFile(path);
}
@ -215,10 +223,9 @@ void MainWindow::connectActionHandlers() {
if (result == QMessageBox::Cancel) return;
if (result == QMessageBox::Save) {
std::optional<std::string> path;
if (!gDataModel->HasFile()) {
if (!gDataModel->HasFile())
path = openFileDialog("Openblocks Level (*.obl)", ".obl", QFileDialog::AcceptSave, QString::fromStdString("Save " + gDataModel->name));
if (!path || path == "") return;
}
if (!path || path == "") return;
gDataModel->SaveToFile(path);
}
@ -235,11 +242,6 @@ void MainWindow::connectActionHandlers() {
gDataModel->Init();
ui->explorerView->updateRoot(gDataModel);
// Reset running state
placeDocument->setRunState(RUN_STOPPED);
undoManager.Reset();
updateToolbars();
// Baseplate
gWorkspace()->AddChild(placeDocument->placeWidget->lastPart = Part::New({
.position = glm::vec3(0, -5, 0),
@ -255,10 +257,9 @@ void MainWindow::connectActionHandlers() {
connect(ui->actionSave, &QAction::triggered, this, [&]() {
std::optional<std::string> path;
if (!editModeDataModel->HasFile()) {
if (!editModeDataModel->HasFile())
path = openFileDialog("Openblocks Level (*.obl)", ".obl", QFileDialog::AcceptSave, QString::fromStdString("Save " + editModeDataModel->name));
if (!path || path == "") return;
}
if (!editModeDataModel->HasFile() && (!path || path == "")) return;
editModeDataModel->SaveToFile(path);
});
@ -286,27 +287,20 @@ void MainWindow::connectActionHandlers() {
// Reset running state
placeDocument->setRunState(RUN_STOPPED);
undoManager.Reset();
updateToolbars();
});
connect(ui->actionDelete, &QAction::triggered, this, [&]() {
UndoState historyState;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (inst.expired()) continue;
historyState.push_back(UndoStateInstanceRemoved { inst.lock(), inst.lock()->GetParent().value() });
inst.lock()->SetParent(std::nullopt);
}
selection->Set({});
historyState.push_back(UndoStateSelectionChanged {selection->Get(), {}});
undoManager.PushState(historyState);
setSelection({});
});
connect(ui->actionCopy, &QAction::triggered, this, [&]() {
pugi::xml_document rootDoc;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (inst.expired()) continue;
inst.lock()->Serialize(rootDoc);
}
@ -318,20 +312,13 @@ void MainWindow::connectActionHandlers() {
mimeData->setData("application/xml", QByteArray::fromStdString(encoded.str()));
QApplication::clipboard()->setMimeData(mimeData);
});
connect(ui->actionCut, &QAction::triggered, this, [&]() {
UndoState historyState;
pugi::xml_document rootDoc;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (inst.expired()) continue;
historyState.push_back(UndoStateInstanceRemoved { inst.lock(), inst.lock()->GetParent().value() });
inst.lock()->Serialize(rootDoc);
inst.lock()->SetParent(std::nullopt);
}
selection->Set({});
historyState.push_back(UndoStateSelectionChanged {selection->Get(), {}});
undoManager.PushState(historyState);
std::ostringstream encoded;
rootDoc.save(encoded);
@ -342,7 +329,6 @@ void MainWindow::connectActionHandlers() {
});
connect(ui->actionPaste, &QAction::triggered, this, [&]() {
UndoState historyState;
const QMimeData* mimeData = QApplication::clipboard()->mimeData();
if (!mimeData || !mimeData->hasFormat("application/xml")) return;
QByteArray bytes = mimeData->data("application/xml");
@ -354,19 +340,14 @@ void MainWindow::connectActionHandlers() {
for (pugi::xml_node instNode : rootDoc.children()) {
result<std::shared_ptr<Instance>, NoSuchInstance> inst = Instance::Deserialize(instNode);
if (!inst) { inst.logError(); continue; }
historyState.push_back(UndoStateInstanceCreated { inst.expect(), gWorkspace() });
gWorkspace()->AddChild(inst.expect());
}
undoManager.PushState(historyState);
});
connect(ui->actionPasteInto, &QAction::triggered, this, [&]() {
UndoState historyState;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() != 1) return;
if (getSelection().size() != 1) return;
std::shared_ptr<Instance> selectedParent = selection->Get()[0];
std::shared_ptr<Instance> selectedParent = getSelection()[0];
const QMimeData* mimeData = QApplication::clipboard()->mimeData();
if (!mimeData || !mimeData->hasFormat("application/xml")) return;
@ -379,22 +360,16 @@ void MainWindow::connectActionHandlers() {
for (pugi::xml_node instNode : rootDoc.children()) {
result<std::shared_ptr<Instance>, NoSuchInstance> inst = Instance::Deserialize(instNode);
if (!inst) { inst.logError(); continue; }
historyState.push_back(UndoStateInstanceCreated { inst.expect(), selectedParent });
selectedParent->AddChild(inst.expect());
}
undoManager.PushState(historyState);
});
connect(ui->actionGroupObjects, &QAction::triggered, this, [&]() {
UndoState historyState;
auto model = Model::New();
std::shared_ptr<Instance> firstParent;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto object : selection->Get()) {
for (auto object : getSelection()) {
if (firstParent == nullptr && object->GetParent().has_value()) firstParent = object->GetParent().value();
historyState.push_back(UndoStateInstanceReparented { object, object->GetParent().value(), model });
object->SetParent(model);
}
@ -404,36 +379,27 @@ void MainWindow::connectActionHandlers() {
// Technically not how it works in the actual studio, but it's not an API-breaking change
// and I think this implementation is more useful so I'm sticking with it
if (firstParent == nullptr) firstParent = gWorkspace();
historyState.push_back(UndoStateInstanceCreated { model, firstParent });
model->SetParent(firstParent);
historyState.push_back(UndoStateSelectionChanged { selection->Get(), { model } });
selection->Set({ model });
playSound("./assets/excluded/electronicpingshort.wav");
setSelection({ model });
});
connect(ui->actionUngroupObjects, &QAction::triggered, this, [&]() {
UndoState historyState;
std::vector<std::shared_ptr<Instance>> newSelection;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto model : selection->Get()) {
for (auto model : getSelection()) {
// Not a model, skip
if (!model->IsA<Model>()) { newSelection.push_back(model); continue; }
for (auto object : model->GetChildren()) {
historyState.push_back(UndoStateInstanceReparented { object, object->GetParent().value(), model->GetParent().value() });
object->SetParent(model->GetParent());
newSelection.push_back(object);
}
historyState.push_back(UndoStateInstanceRemoved { model, model->GetParent().value() });
model->SetParent(std::nullopt);
model->Destroy();
}
historyState.push_back(UndoStateSelectionChanged { selection->Get(), newSelection });
selection->Set(newSelection);
playSound("./assets/excluded/electronicpingshort.wav");
setSelection(newSelection);
});
connect(ui->actionSaveModel, &QAction::triggered, this, [&]() {
@ -445,8 +411,7 @@ void MainWindow::connectActionHandlers() {
pugi::xml_document modelDoc;
pugi::xml_node modelRoot = modelDoc.append_child("openblocks");
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
for (std::weak_ptr<Instance> inst : getSelection()) {
if (inst.expired()) continue;
inst.lock()->Serialize(modelRoot);
}
@ -455,10 +420,8 @@ void MainWindow::connectActionHandlers() {
});
connect(ui->actionInsertModel, &QAction::triggered, this, [&]() {
UndoState historyState;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() != 1) return;
std::shared_ptr<Instance> selectedParent = selection->Get()[0];
if (getSelection().size() != 1) return;
std::shared_ptr<Instance> selectedParent = getSelection()[0];
std::optional<std::string> path = openFileDialog("Openblocks Model (*.obm)", ".obm", QFileDialog::AcceptOpen);
if (!path) return;
@ -470,23 +433,9 @@ void MainWindow::connectActionHandlers() {
for (pugi::xml_node instNode : modelDoc.child("openblocks").children("Item")) {
result<std::shared_ptr<Instance>, NoSuchInstance> inst = Instance::Deserialize(instNode);
if (!inst) { inst.logError(); continue; }
historyState.push_back(UndoStateInstanceCreated { inst.expect(), selectedParent });
selectedParent->AddChild(inst.expect());
}
});
connect(ui->actionUndo, &QAction::triggered, this, [&]() {
undoManager.Undo();
});
connect(ui->actionRedo, &QAction::triggered, this, [&]() {
undoManager.Redo();
});
connect(ui->actionAbout, &QAction::triggered, this, [this]() {
AboutDialog* aboutDialog = new AboutDialog(this);
aboutDialog->open();
});
}
void MainWindow::openFile(std::string path) {
@ -503,10 +452,9 @@ void MainWindow::openFile(std::string path) {
if (result == QMessageBox::Cancel) return;
if (result == QMessageBox::Save) {
std::optional<std::string> path;
if (!gDataModel->HasFile()) {
if (!gDataModel->HasFile())
path = openFileDialog("Openblocks Level (*.obl)", ".obl", QFileDialog::AcceptSave, QString::fromStdString("Save " + gDataModel->name));
if (!path || path == "") return;
}
if (!path || path == "") return;
gDataModel->SaveToFile(path);
}
@ -555,9 +503,6 @@ void MainWindow::updateToolbars() {
ui->actionRunSimulation->setEnabled(placeDocument->runState() != RUN_RUNNING);
ui->actionPauseSimulation->setEnabled(placeDocument->runState() == RUN_RUNNING);
ui->actionStopSimulation->setEnabled(placeDocument->runState() != RUN_STOPPED);
ui->actionUndo->setEnabled(undoManager.CanUndo() && placeDocument->runState() == RUN_STOPPED);
ui->actionRedo->setEnabled(undoManager.CanRedo() && placeDocument->runState() == RUN_STOPPED);
}
std::optional<std::string> MainWindow::openFileDialog(QString filter, QString defaultExtension, QFileDialog::AcceptMode acceptMode, QString title) {

View file

@ -6,7 +6,6 @@
#include "qbasictimer.h"
#include "qcoreevent.h"
#include "script/scriptdocument.h"
#include "undohistory.h"
#include <QMainWindow>
#include <QLineEdit>
#include <map>
@ -50,8 +49,6 @@ class MainWindow : public QMainWindow
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
UndoHistory undoManager;
SelectedTool selectedTool;
GridSnappingMode snappingMode;
@ -63,8 +60,6 @@ public:
void openFile(std::string path);
Ui::MainWindow *ui;
friend PlaceDocument;
private:
PlaceDocument* placeDocument;
std::map<std::shared_ptr<Script>, ScriptDocument*> scriptDocuments;

View file

@ -78,15 +78,8 @@
<addaction name="actionPasteInto"/>
<addaction name="actionDelete"/>
</widget>
<widget class="QMenu" name="menuHelp">
<property name="title">
<string>Help</string>
</property>
<addaction name="actionAbout"/>
</widget>
<addaction name="menuFile"/>
<addaction name="menuEdit"/>
<addaction name="menuHelp"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<widget class="QDockWidget" name="explorerWidget">
@ -151,8 +144,6 @@
<addaction name="actionNew"/>
<addaction name="actionOpen"/>
<addaction name="actionSave"/>
<addaction name="actionUndo"/>
<addaction name="actionRedo"/>
</widget>
<widget class="QToolBar" name="transformTools">
<property name="windowTitle">
@ -813,39 +804,6 @@
<enum>QAction::MenuRole::NoRole</enum>
</property>
</action>
<action name="actionAbout">
<property name="text">
<string>About...</string>
</property>
</action>
<action name="actionUndo">
<property name="icon">
<iconset theme="edit-undo"/>
</property>
<property name="text">
<string>Undo</string>
</property>
<property name="shortcut">
<string>Ctrl+Z</string>
</property>
<property name="menuRole">
<enum>QAction::MenuRole::NoRole</enum>
</property>
</action>
<action name="actionRedo">
<property name="icon">
<iconset theme="edit-redo"/>
</property>
<property name="text">
<string>Redo</string>
</property>
<property name="shortcut">
<string>Ctrl+Y</string>
</property>
<property name="menuRole">
<enum>QAction::MenuRole::NoRole</enum>
</property>
</action>
</widget>
<customwidgets>
<customwidget>

View file

@ -5,8 +5,6 @@
#include "objects/base/instance.h"
#include "objects/meta.h"
#include "objects/script.h"
#include "objects/service/selection.h"
#include "undohistory.h"
#include <memory>
#include <qaction.h>
#include <qtreeview.h>
@ -39,10 +37,6 @@ ExplorerView::ExplorerView(QWidget* parent):
});
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection &selected, const QItemSelection &deselected) {
// Simple, good old debounce.
if (handlingSelectionUpdate)
return;
std::vector<std::shared_ptr<Instance>> selectedInstances;
selectedInstances.reserve(selectedIndexes().count()); // This doesn't reserve everything, but should enhance things anyway
@ -50,23 +44,20 @@ ExplorerView::ExplorerView(QWidget* parent):
selectedInstances.push_back(reinterpret_cast<Instance*>(index.internalPointer())->shared_from_this());
}
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
selection->Set(selectedInstances);
::setSelection(selectedInstances, true);
});
}
addSelectionListener([&](auto oldSelection, auto newSelection, bool fromExplorer) {
// It's from us, ignore it.
if (fromExplorer) return;
void ExplorerView::setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection) {
handlingSelectionUpdate = true;
this->clearSelection();
for (std::weak_ptr<Instance> inst : selection) {
if (inst.expired()) continue;
QModelIndex index = this->model.ObjectToIndex(inst.lock());
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select);
}
handlingSelectionUpdate = false;
this->clearSelection();
for (std::weak_ptr<Instance> inst : newSelection) {
if (inst.expired()) continue;
QModelIndex index = this->model.ObjectToIndex(inst.lock());
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select);
}
});
}
ExplorerView::~ExplorerView() {
@ -112,12 +103,10 @@ void ExplorerView::buildContextMenu() {
QAction* instAction = new QAction(model.iconOf(type), QString::fromStdString(type->className));
insertObjectMenu->addAction(instAction);
connect(instAction, &QAction::triggered, this, [&]() {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() == 0) return;
std::shared_ptr<Instance> instParent = selection->Get()[0];
if (getSelection().size() == 0) return;
std::shared_ptr<Instance> instParent = getSelection()[0];
std::shared_ptr<Instance> newInst = type->constructor();
newInst->SetParent(instParent);
M_mainWindow->undoManager.PushState({ UndoStateInstanceCreated { newInst, instParent } });
});
}
}

View file

@ -1,14 +1,12 @@
#pragma once
#include "panes/explorermodel.h"
#include <memory>
#include <qmenu.h>
#include <qtreeview.h>
class Ui_MainWindow;
class ExplorerView : public QTreeView {
bool handlingSelectionUpdate = false;
public:
ExplorerView(QWidget* parent = nullptr);
~ExplorerView() override;
@ -19,8 +17,6 @@ public:
void buildContextMenu();
void updateRoot(std::shared_ptr<Instance> newRoot);
void setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection);
private:
ExplorerModel model;
QMenu contextMenu;

View file

@ -4,9 +4,7 @@
#include "datatypes/variant.h"
#include "datatypes/primitives.h"
#include "error/data.h"
#include "mainwindow.h"
#include "objects/base/member.h"
#include "undohistory.h"
#include <QColorDialog>
#include <QComboBox>
@ -57,7 +55,7 @@ public:
std::string propertyName = !isComposite ? view->itemFromIndex(index)->data(0, Qt::DisplayRole).toString().toStdString()
: view->itemFromIndex(index.parent())->data(0, Qt::DisplayRole).toString().toStdString();
PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect();
Variant currentValue = inst->GetProperty(propertyName).expect();
Variant currentValue = inst->GetPropertyValue(propertyName).expect();
if (isComposite) {
if (meta.type.descriptor == &Vector3::TYPE) {
@ -146,7 +144,7 @@ public:
std::string propertyName = !index.parent().parent().isValid() ? view->itemFromIndex(index)->data(0, Qt::DisplayRole).toString().toStdString()
: view->itemFromIndex(index.parent())->data(0, Qt::DisplayRole).toString().toStdString();
PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect();
Variant currentValue = inst->GetProperty(propertyName).expect();
Variant currentValue = inst->GetPropertyValue(propertyName).expect();
if (isComposite) {
if (meta.type.descriptor == &Vector3::TYPE) {
@ -208,19 +206,17 @@ public:
: view->itemFromIndex(index.parent())->data(0, Qt::DisplayRole).toString().toStdString();
PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect();
Variant oldValue = inst->GetProperty(propertyName).expect();
if (isComposite) {
if (meta.type.descriptor == &Vector3::TYPE) {
QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(editor);
float value = spinBox->value();
Vector3 prev = inst->GetProperty(propertyName).expect().get<Vector3>();
Vector3 prev = inst->GetPropertyValue(propertyName).expect().get<Vector3>();
Vector3 newVector = componentName == "X" ? Vector3(value, prev.Y(), prev.Z())
: componentName == "Y" ? Vector3(prev.X(), value, prev.Z())
: componentName == "Z" ? Vector3(prev.X(), prev.Y(), value) : prev;
inst->SetProperty(propertyName, newVector).expect();
inst->SetPropertyValue(propertyName, newVector).expect();
view->rebuildCompositeProperty(view->itemFromIndex(index.parent()), &Vector3::TYPE, newVector);
return;
}
@ -231,24 +227,24 @@ public:
if (meta.type.descriptor == &FLOAT_TYPE) {
QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(editor);
inst->SetProperty(propertyName, (float)spinBox->value()).expect();
inst->SetPropertyValue(propertyName, (float)spinBox->value()).expect();
model->setData(index, spinBox->value());
} else if (meta.type.descriptor == &INT_TYPE) {
QSpinBox* spinBox = dynamic_cast<QSpinBox*>(editor);
inst->SetProperty(propertyName, (int)spinBox->value()).expect();
inst->SetPropertyValue(propertyName, (int)spinBox->value()).expect();
model->setData(index, spinBox->value());
} else if (meta.type.descriptor == &STRING_TYPE) {
QLineEdit* lineEdit = dynamic_cast<QLineEdit*>(editor);
inst->SetProperty(propertyName, lineEdit->text().toStdString()).expect();
inst->SetPropertyValue(propertyName, lineEdit->text().toStdString()).expect();
model->setData(index, lineEdit->text());
} else if (meta.type.descriptor == &Color3::TYPE) {
QColorDialog* colorDialog = dynamic_cast<QColorDialog*>(editor);
QColor color = colorDialog->currentColor();
Color3 color3(color.redF(), color.greenF(), color.blueF());
inst->SetProperty(propertyName, color3).expect();
inst->SetPropertyValue(propertyName, color3).expect();
model->setData(index, QString::fromStdString(color3.ToString()), Qt::DisplayRole);
model->setData(index, color, Qt::DecorationRole);
} else if (meta.type.descriptor == &EnumItem::TYPE) {
@ -256,7 +252,7 @@ public:
std::vector<EnumItem> siblingItems = meta.type.enum_->GetEnumItems();
EnumItem newItem = siblingItems[comboBox->currentIndex()];
inst->SetProperty(propertyName, newItem).expect("Failed to set enum value in properties pane");
inst->SetPropertyValue(propertyName, newItem).expect("Failed to set enum value in properties pane");
model->setData(index, QString::fromStdString(newItem.Name()), Qt::DisplayRole);
} else if (meta.type.descriptor->fromString) {
QLineEdit* lineEdit = dynamic_cast<QLineEdit*>(editor);
@ -264,19 +260,16 @@ public:
result<Variant, DataParseError> parsedResult = meta.type.descriptor->fromString(lineEdit->text().toStdString(), meta.type);
if (!parsedResult) return;
Variant parsedValue = parsedResult.expect();
inst->SetProperty(propertyName, parsedValue).expect();
inst->SetPropertyValue(propertyName, parsedValue).expect();
model->setData(index, QString::fromStdString(parsedValue.ToString()));
view->rebuildCompositeProperty(view->itemFromIndex(index), meta.type.descriptor, parsedValue);
}
Variant newValue = inst->GetProperty(propertyName).expect();
view->undoManager->PushState({ UndoStatePropertyChanged { inst, propertyName, oldValue, newValue } });
}
};
PropertiesView::PropertiesView(QWidget* parent):
QTreeWidget(parent) {
clear();
setHeaderHidden(true);
setColumnCount(2);
@ -307,10 +300,6 @@ QStringList PROPERTY_CATEGORY_NAMES {
"Surface Inputs",
};
void PropertiesView::init() {
undoManager = &dynamic_cast<MainWindow*>(window())->undoManager;
}
QModelIndex PropertiesView::indexAt(const QPoint &point) const {
return QTreeWidget::indexAt(point + QPoint(indentation(), 0));
}
@ -353,7 +342,7 @@ void PropertiesView::setSelected(std::optional<std::shared_ptr<Instance>> instan
for (std::string property : properties) {
PropertyMeta meta = inst->GetPropertyMeta(property).expect();
Variant currentValue = inst->GetProperty(property).expect();
Variant currentValue = inst->GetPropertyValue(property).expect();
if (meta.type.descriptor == &CFrame::TYPE || meta.flags & PROP_HIDDEN) continue;
@ -412,8 +401,7 @@ void PropertiesView::propertyChanged(QTreeWidgetItem *item, int column) {
PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect();
if (meta.type.descriptor == &BOOL_TYPE) {
inst->SetProperty(propertyName, item->checkState(1) == Qt::Checked).expect();
undoManager->PushState({ UndoStatePropertyChanged { inst, propertyName, item->checkState(1) != Qt::Checked, item->checkState(1) == Qt::Checked } });
inst->SetPropertyValue(propertyName, item->checkState(1) == Qt::Checked).expect();
}
}
@ -450,7 +438,7 @@ void PropertiesView::onPropertyUpdated(std::shared_ptr<Instance> inst, std::stri
// lastUpdateTime = std::chrono::steady_clock::now();
PropertyMeta meta = inst->GetPropertyMeta(property).expect();
Variant currentValue = inst->GetProperty(property).expect();
Variant currentValue = inst->GetPropertyValue(property).expect();
if (meta.type.descriptor == &CFrame::TYPE) return;

View file

@ -3,7 +3,6 @@
#include <QTreeWidget>
#include "datatypes/base.h"
#include "objects/base/instance.h"
#include "undohistory.h"
class Ui_MainWindow;
class PropertiesItemDelegate;
@ -19,8 +18,6 @@ class PropertiesView : public QTreeWidget {
void rebuildCompositeProperty(QTreeWidgetItem *item, const TypeDesc*, Variant);
void onPropertyUpdated(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
UndoHistory* undoManager;
friend PropertiesItemDelegate;
protected:
void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override;
@ -29,7 +26,5 @@ public:
PropertiesView(QWidget* parent = nullptr);
~PropertiesView() override;
void init();
void setSelected(std::optional<std::shared_ptr<Instance>> instance);
};

View file

@ -1,11 +1,10 @@
#include "placedocument.h"
#include "common.h"
#include "datatypes/variant.h"
#include "mainglwidget.h"
#include "mainwindow.h"
#include "objects/joint/snap.h"
#include "objects/script.h"
#include "objects/service/script/scriptcontext.h"
#include "objects/script/scriptcontext.h"
#include "enum/surface.h"
#include <cstdio>
#include <memory>
@ -16,8 +15,6 @@
#include <qmdisubwindow.h>
#include <qlayout.h>
#include <qmimedata.h>
#include "../ui_mainwindow.h"
#include "objects/service/selection.h"
PlaceDocument::PlaceDocument(QWidget* parent):
QMdiSubWindow(parent) {
@ -27,7 +24,6 @@ PlaceDocument::PlaceDocument(QWidget* parent):
setWindowTitle("Place");
_runState = RUN_STOPPED;
updateSelectionListeners(gDataModel->GetService<Selection>());
}
PlaceDocument::~PlaceDocument() {
@ -45,36 +41,16 @@ void PlaceDocument::setRunState(RunState newState) {
std::shared_ptr<DataModel> newModel = editModeDataModel->CloneModel();
gDataModel = newModel;
gDataModel->Init(true);
updateSelectionListeners(gDataModel->GetService<Selection>());
} else if (newState == RUN_PAUSED && _runState == RUN_RUNNING) {
_runState = RUN_PAUSED;
} else if (newState == RUN_STOPPED) {
_runState = RUN_STOPPED;
// TODO: GC: Check to make sure gDataModel gets properly garbage collected prior to this
// GC: Check to make sure gDataModel gets properly garbage collected prior to this
gDataModel = editModeDataModel;
updateSelectionListeners(gDataModel->GetService<Selection>());
}
}
void PlaceDocument::updateSelectionListeners(std::shared_ptr<Selection> selection) {
MainWindow* mainWnd = dynamic_cast<MainWindow*>(window());
if (!selectionConnection.expired())
selectionConnection.lock()->Disconnect();
selectionConnection = selection->SelectionChanged->Connect([selection, mainWnd](std::vector<Variant> _){
// Update properties
if (selection->Get().size() != 1)
mainWnd->ui->propertiesView->setSelected(std::nullopt);
else
mainWnd->ui->propertiesView->setSelected(selection->Get()[0]);
// Update explorer
mainWnd->ui->explorerView->setSelectedObjects(selection->Get());
});
}
void PlaceDocument::closeEvent(QCloseEvent *closeEvent) {
// Placeholder
closeEvent->ignore();

View file

@ -1,13 +1,10 @@
#pragma once
#include "datatypes/signal.h"
#include "mainglwidget.h"
#include <qevent.h>
#include <qmdisubwindow.h>
#include <QBasicTimer>
class Selection;
enum RunState {
RUN_STOPPED,
RUN_RUNNING,
@ -18,10 +15,7 @@ class PlaceDocument : public QMdiSubWindow {
QBasicTimer timer;
RunState _runState;
std::weak_ptr<SignalConnection> selectionConnection;
void timerEvent(QTimerEvent*) override;
void updateSelectionListeners(std::shared_ptr<Selection>);
public:
MainGLWidget* placeWidget;
PlaceDocument(QWidget* parent = nullptr);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

View file

@ -1,81 +0,0 @@
#include "undohistory.h"
#include "common.h"
#include "objects/service/selection.h"
void UndoHistory::PushState(UndoState state) {
if (processingUndo) return; // Ignore PushState requests when changes are initiated by us
redoHistory = {};
if (maxBufferSize != -1 && (int)undoHistory.size() > maxBufferSize)
undoHistory.erase(undoHistory.begin(), undoHistory.begin()+maxBufferSize-(int)undoHistory.size()-1);
undoHistory.push_back(state);
undoStateListener();
}
void UndoHistory::Undo() {
if (undoHistory.size() == 0) return;
UndoState state = undoHistory.back();
undoHistory.pop_back();
redoHistory.push(state);
processingUndo = true;
for (UndoStateChange& change : state) {
// https://stackoverflow.com/a/63483353
if (auto v = std::get_if<UndoStatePropertyChanged>(&change)) {
// The old value used to be valid, so it still should be...
v->affectedInstance->SetProperty(v->property, v->oldValue).expect();
} else if (auto v = std::get_if<UndoStateInstanceCreated>(&change)) {
v->instance->SetParent(std::nullopt);
} else if (auto v = std::get_if<UndoStateInstanceRemoved>(&change)) {
v->instance->SetParent(v->oldParent);
} else if (auto v = std::get_if<UndoStateInstanceReparented>(&change)) {
v->instance->SetParent(v->oldParent);
} else if (auto v = std::get_if<UndoStateSelectionChanged>(&change)) {
gDataModel->GetService<Selection>()->Set(v->oldSelection);
}
}
processingUndo = false;
undoStateListener();
}
void UndoHistory::Redo() {
if (redoHistory.size() == 0) return;
UndoState state = redoHistory.top();
redoHistory.pop();
undoHistory.push_back(state);
processingUndo = true;
for (UndoStateChange& change : state) {
// https://stackoverflow.com/a/63483353
if (auto v = std::get_if<UndoStatePropertyChanged>(&change)) {
// The old value used to be valid, so it still should be...
v->affectedInstance->SetProperty(v->property, v->newValue).expect();
} else if (auto v = std::get_if<UndoStateInstanceCreated>(&change)) {
v->instance->SetParent(v->newParent);
} else if (auto v = std::get_if<UndoStateInstanceRemoved>(&change)) {
v->instance->SetParent(std::nullopt);
} else if (auto v = std::get_if<UndoStateInstanceReparented>(&change)) {
v->instance->SetParent(v->newParent);
} else if (auto v = std::get_if<UndoStateSelectionChanged>(&change)) {
gDataModel->GetService<Selection>()->Set(v->newSelection);
}
}
processingUndo = false;
undoStateListener();
}
void UndoHistory::Reset() {
processingUndo = false;
undoHistory.clear();
redoHistory = {};
undoStateListener();
}
void UndoHistory::SetUndoStateListener(UndoStateChangedListener listener) {
undoStateListener = listener;
}

View file

@ -1,61 +0,0 @@
#pragma once
#include "datatypes/signal.h"
#include "datatypes/variant.h"
#include "objects/base/instance.h"
#include "utils.h"
#include <deque>
#include <memory>
#include <stack>
struct UndoStatePropertyChanged {
std::shared_ptr<Instance> affectedInstance;
std::string property;
Variant oldValue;
Variant newValue;
};
struct UndoStateInstanceCreated {
std::shared_ptr<Instance> instance;
std::shared_ptr<Instance> newParent;
};
struct UndoStateInstanceRemoved {
std::shared_ptr<Instance> instance;
std::shared_ptr<Instance> oldParent;
};
struct UndoStateInstanceReparented {
std::shared_ptr<Instance> instance;
nullable std::shared_ptr<Instance> oldParent;
nullable std::shared_ptr<Instance> newParent;
};
struct UndoStateSelectionChanged {
std::vector<std::shared_ptr<Instance>> oldSelection;
std::vector<std::shared_ptr<Instance>> newSelection;
};
typedef std::variant<UndoStatePropertyChanged, UndoStateInstanceCreated, UndoStateInstanceRemoved, UndoStateInstanceReparented, UndoStateSelectionChanged> UndoStateChange;
typedef std::vector<UndoStateChange> UndoState;
typedef std::function<void()> UndoStateChangedListener;
class UndoHistory {
// Ignore PushState requests
bool processingUndo = false;
std::deque<UndoState> undoHistory;
std::stack<UndoState> redoHistory;
UndoStateChangedListener undoStateListener;
public:
int maxBufferSize = 100;
void PushState(UndoState);
void Undo();
void Redo();
void Reset();
inline bool CanUndo() { return !undoHistory.empty(); }
inline bool CanRedo() { return !redoHistory.empty(); }
void SetUndoStateListener(UndoStateChangedListener listener);
};