Merge remote-tracking branch 'origin/v0.6.0' into v0.7.0

# Conflicts:
#	src/ifcgeom/IfcGeomTree.h
#	src/ifcgeom_schema_agnostic/IfcGeomIterator.h
#	src/ifcgeom_schema_agnostic/IteratorImplementation.cpp
#	src/ifcgeom_schema_agnostic/IteratorImplementation.h
#	src/ifcparse/Ifc4x3_rc3.cpp
#	src/ifcparse/Ifc4x3_rc3.h
#	src/serializers/SvgSerializer.cpp
This commit is contained in:
Thomas Krijnen
2021-08-10 14:30:07 +02:00
299 changed files with 23606 additions and 2849 deletions
+1
View File
@@ -1,3 +1,4 @@
# These are supported funding model platforms
github: [aothms]
open_collective: opensourcebim
+2 -2
View File
@@ -59,8 +59,8 @@ jobs:
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file: src/blenderbim_${{ matrix.config.short_name }}_${{ matrix.pyver }}/dist/blender28-bim-${{steps.date.outputs.date}}-${{ matrix.pyver }}-${{ matrix.config.short_name }}.zip
asset_name: blender28-bim-${{steps.date.outputs.date}}-${{ matrix.pyver }}-${{ matrix.config.short_name }}.zip
file: src/blenderbim_${{ matrix.config.short_name }}_${{ matrix.pyver }}/dist/blenderbim-${{steps.date.outputs.date}}-${{ matrix.pyver }}-${{ matrix.config.short_name }}.zip
asset_name: blenderbim-${{steps.date.outputs.date}}-${{ matrix.pyver }}-${{ matrix.config.short_name }}.zip
tag: "blenderbim-${{steps.date.outputs.date}}"
overwrite: true
body: "Daily developer testing build blenderbim-${{steps.date.outputs.date}}"
+17
View File
@@ -31,4 +31,21 @@ Pipfile.lock
# Vim
*.swp
# Flask
instance/*
!instance/.gitignore
.webassets-cache
.env
*.db
# Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class
# pipenv
Pipfile
Pipfile.lock
# Database
*.db
+2 -2
View File
@@ -1,7 +1,7 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
@@ -618,4 +618,4 @@ an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
END OF TERMS AND CONDITIONS
+1 -1
View File
@@ -1,7 +1,7 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
+38 -1
View File
@@ -217,7 +217,44 @@ Usage examples
>>> # Writing IFC-SPF files to disk:
>>> f.write("out.ifc")
[LGPL]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/COPYING "LGPL"
Extra tools
-----------
Also available are a series of utilities that are based on or related to IfcOpenShell.
Those marked with an asterisk are part of IfcOpenShell.
Name | License
--- | ---
bcf | LGPL-3.0-or-later
blenderbim | GPL-3.0-or-later
bsdd | LGPL-3.0-or-later
ifc2ca | LGPL-3.0-or-later
ifc4d | LGPL-3.0-or-later
ifc5d | LGPL-3.0-or-later
ifcbimtester | LGPL-3.0-or-later
ifcblender | LGPL-3.0-or-later\*
ifccityjson | LGPL-3.0-or-later
ifcclash | LGPL-3.0-or-later
ifccobie | LGPL-3.0-or-later
ifcconvert | LGPL-3.0-or-later\*
ifccsv | LGPL-3.0-or-later
ifcdiff | LGPL-3.0-or-later
ifcfm | LGPL-3.0-or-later
ifcgeom | LGPL-3.0-or-later\*
ifcgeom\_schema\_agnostic | LGPL-3.0-or-later\*
ifcgeomserver | LGPL-3.0-or-later\*
ifcjni | LGPL-3.0-or-later\*
ifcmax | LGPL-3.0-or-later\*
ifcopenshell-python | LGPL-3.0-or-later\*
ifcparse | LGPL-3.0-or-later\*
ifcpatch | LGPL-3.0-or-later
ifcsverchok | GPL-3.0-or-later
ifcwrap | LGPL-3.0-or-later\*
qtviewer | LGPL-3.0-or-later\*
serializers | LGPL-3.0-or-later\*
[LGPL]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/COPYING.LESSER "LGPL-3.0-or-later"
[IFC]: https://technical.buildingsmart.org/standards/ifc/ "IFC"
[IFC2x3 TC1]: https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML/ "IFC2x3 TC1"
[IFC4 Add2 TC1]: https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/HTML/ "IFC4 Add2 TC1"
+621
View File
@@ -0,0 +1,621 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
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 that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU 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 as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+40 -2
View File
@@ -7,13 +7,13 @@ is available via `bcfapi.py`.
- BCF-XML version 2.1: Fully supported
- BCF-API version 2.1: Not supported, will probably tackle this after BCF-API v3.0
- BCF-XML version 3.0: Almost fully supported, except for the documents module
- BCF-API version 3.0: Not supported, but work underway to support it
- BCF-API version 3.0: Almost fully supported, except for two requests.
## bcfxml
The `bcfxml` module lets you interact with the BCF-XML standard.
```
```python
from bcf import bcfxml
@@ -60,3 +60,41 @@ topic = bcfxml.get_topic(guid)
topic.title = "New title"
bcfxml.edit_topic(topic)
```
## bcfapi
The `bcfapi` module lets you interact with the BCF-API standard.
```python
from bcf.v3.bcfapi import FoundationClient, BcfClient
foundation_client = FoundationClient("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "OPENCDE_BASEURL")
auth_methods = foundation_client.get_auth_methods()
# Our library currently only implements the authorization_code flow
if "authorization_code" in auth_methods:
auth_client.login()
bcf_client = BcfClient()
versions = foundation_client.get_versions()
for version in versions:
if "3.0" in versions:
if version["api_id"] == "bcf" and version["version_id"] == "3.0":
bcf_client.set_version(version)
data = bcf_client.get_projects()
print(data)
project_id = data[0]["project_id"]
print(project_id)
data = bcf_client.get_project(project_id)
print(data)
data = bcf_client.get_extensions(project_id)
print(data)
```
## Todo List
The remaining work that needs to be completed in `bcfxml.py` and `bcfapi.py`.
* For `bcfxml.py` two xsds support is remaining namely 'documents.xsd` and `extensions.xsd`.
* For `bcfapi.py` two requests that are `get_topics` and `get_comments` are remaining.
+536
View File
@@ -0,0 +1,536 @@
import uuid
import time
import json
import urllib
import requests
import webbrowser
import http.server
import base64
client_id, client_secret = "", ""
class OAuthReceiver(http.server.BaseHTTPRequestHandler):
def do_GET(self):
query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
self.server.auth_code = query.get("code", [""])[0]
self.server.auth_state = query.get("state", [""])[0]
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("You have now authenticated :) You may now close this browser window.".encode("utf-8"))
class FoundationClient:
def __init__(self, client_id, client_secret, base_url=None, redirect_subdir=None):
self.baseurl = base_url
self.access_token = ""
self.refresh_token = ""
self.access_token_expires_on = time.time()
self.refresh_token_expires_on = float("inf")
self.auth_endpoint = None
self.token_endpoint = None
self.client_id = client_id
self.client_secret = client_secret
self.auth_method = None
self.redirect_subdir = redirect_subdir
def get_access_token(self):
if self.access_token and self.access_token_expires_on > time.time():
return self.access_token
elif self.refresh_token and self.refresh_token_expires_on > time.time():
self.get_refresh_token()
else:
self.login()
return self.access_token
def get_auth_methods(self):
resp = requests.get(f"{self.baseurl}foundation/1.0/auth")
return resp.json()["supported_oauth2_flows"]
def get_versions(self):
resp = requests.get(f"{self.baseurl}foundation/versions")
return resp.json()["versions"]
def login(self):
resp = requests.get(f"{self.baseurl}foundation/1.0/auth")
values = resp.json()
self.auth_endpoint = values["oauth2_auth_url"]
self.token_endpoint = values["oauth2_token_url"]
with http.server.HTTPServer(("", 8080), OAuthReceiver) as server:
state = str(uuid.uuid4())
query = urllib.parse.urlencode(
{
"client_id": self.client_id,
"response_type": "code",
"state": state,
"redirect_uri": f"http://localhost:{server.server_address[1]}/{self.redirect_subdir}",
}
)
if "?" in self.auth_endpoint:
webbrowser.open(f"{self.auth_endpoint}&{query}")
else:
webbrowser.open(f"{self.auth_endpoint}?{query}")
server.timeout = 100
server.state = state
server.handle_request()
if server.auth_code and server.auth_state == state:
data = {
"grant_type": "authorization_code",
"code": server.auth_code,
"redirect_uri": f"http://localhost:{server.server_address[1]}/{self.redirect_subdir}",
}
auth_string = f"{self.client_id}:{self.client_secret}"
header_string = base64.b64encode(auth_string.encode("utf-8")).decode("utf-8")
headers = {"Authorization": f"Basic {header_string}"}
self.set_tokens_from_response(requests.post(self.token_endpoint, data=data, headers=headers))
def get_refresh_token(self):
self.set_tokens_from_response(
requests.post(
self.token_endpoint,
params={
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
},
).json()
)
def get_new_access_token(self):
auth_string = f"{self.client_id}:{self.client_secret}"
header_string = base64.b64encode(auth_string.encode("utf-8")).decode("utf-8")
headers = {"Authorization": f"Basic {header_string}"}
self.set_tokens_from_response(
requests.post(
self.token_endpoint,
data={
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
},
headers=headers,
).json()
)
def set_auth_method(self, method="authorization_code_grant"):
if method != "authorization_code_grant":
raise NotImplementedError(f"{method} not supported")
else:
self.auth_method = method
def set_tokens_from_response(self, response):
response = response.json()
self.access_token = response["access_token"]
self.refresh_token = response["refresh_token"]
self.access_token_expires_on = time.time() + response["expires_in"]
if "refresh_token_expires_in" in response:
self.refresh_token_expires_on = time.time() + response["refresh_token_expires_in"]
class BcfClient:
def __init__(self, foundation_client):
self.foundation_client = foundation_client
self.version_id = None
self.baseurl = None
def set_version(self, version):
self.version_id = version["version_id"]
self.baseurl = version["api_base_url"]
def get(self, endpoint, params=None, is_auth_required=False):
headers = {"Authorization": "Bearer " + self.foundation_client.get_access_token()}
return requests.get(f"{self.baseurl}{endpoint}", headers=headers, params=params or None).json()
def post(self, endpoint, data=None, params=None):
headers = {
"Authorization": "Bearer " + self.foundation_client.get_access_token(),
"Content-type": "application/json",
}
resp = requests.post(
f"{self.baseurl}{endpoint}",
headers=headers,
params=params or None,
data=data or None,
)
return resp.status_code, resp.text
def put(self, endpoint, data=None, params=None):
headers = {
"Authorization": "Bearer " + self.foundation_client.get_access_token(),
"Content-type": "application/json",
}
resp = requests.put(
f"{self.baseurl}{endpoint}",
headers=headers,
params=params or None,
data=data or None,
)
return resp.status_code, resp.text
def delete(self, endpoint, params=None):
headers = {"Authorization": "Bearer " + self.foundation_client.get_access_token()}
resp = requests.put(
f"{self.baseurl}{endpoint}",
headers=headers,
params=params or None,
)
return resp.status_code
def get_projects(self) -> list:
return self.get(
f"/projects",
)
def get_project(
self,
project_id="",
) -> dict:
return self.get(
f"/projects/{project_id}",
{
"project_id": project_id,
},
)
def update_project(self, project_id="", data=None) -> dict:
url = f"{self.baseurl}/projects/{project_id}"
headers = {"Authorization": "Bearer " + self.foundation_client.get_access_token()}
resp = requests.put(url, headers=headers, data=data)
return resp.status_code, resp.text
def get_extensions(
self,
project_id="",
) -> dict:
return self.get(
f"/projects/{project_id}/extensions",
{
"project_id": project_id,
},
)
def get_topics(
self,
project_id="",
topics="",
query_string=None,
) -> list:
# return self.get(
# f"/projects/{project_id}/topics",
# {
# "project_id": project_id,
# "topics": topics,
# "query_string": query_string,
# },
# )
pass
def get_topic(self, project_id="", topic_id="") -> dict:
return self.get(
f"/projects/{project_id}/topics/{topic_id}",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def create_topic(self, project_id="", data=None):
return self.post(f"/projects/{project_id}/topics", data=data)
def update_topic(self, project_id="", topic_id="", data=None) -> dict:
return self.put(f"/projects/{project_id}/topics/{topic_id}", data=data)
def delete_topic(self, project_id="", topic_id=""):
return self.delete(f"/projects/{project_id}/topics/{topic_id}")
def get_snippet(self, project_id="", topic_id="") -> str:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/snippet",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def update_snippet(self, project_id="", topic_id="", data=None):
return self.put(f"/projects/{project_id}/topics", data=data)
def get_files_information(self, project_id="") -> list:
return self.get(
f"/projects/{project_id}/files_information",
{
"project_id": project_id,
},
)
def get_files(self, project_id="", topic_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/files",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def update_files(
self,
project_id="",
topic_id="",
data=None,
params=None,
):
return self.put(
f"/projects/{project_id}/topics/{topic_id}/files",
data=data,
)
def get_comments(self, project_id="", topic_id="") -> list:
pass
def create_comments(
self,
project_id="",
topic_id="",
data=None,
params=None,
):
return self.post(
f"/projects/{project_id}/topics/{topic_id}/comments",
data=data,
)
def get_comment(self, project_id="", topic_id="", comment_id="") -> dict:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/comments/{comment_id}",
{
"project_id": project_id,
"topic_id": topic_id,
"comment_id": comment_id,
},
)
def delete_comment(self, project_id="", topic_id="", comment_id=""):
return self.delete(f"/projects/{project_id}/topics/{topic_id}/comments/{comment_id}")
def update_comment(
self,
project_id="",
topic_id="",
comment_id="",
data=None,
):
return self.put(
f"/projects/{project_id}/topics/{topic_id}/comments/{comment_id}",
data=data,
)
def get_viewpoints(self, project_id="", topic_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def create_viewpoints(self, project_id="", topic_id="", data=None):
return self.post(
f"/projects/{project_id}/topics/{topic_id}/viewpoints",
data=data,
)
def get_viewpoint(self, project_id="", topic_id="", viewpoint_id="") -> dict:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}",
{
"project_id": project_id,
"topic_id": topic_id,
"viewpoint_id": viewpoint_id,
},
)
def delete_viewpoint(
self,
project_id="",
topic_id="",
viewpoint_id="",
):
return self.delete(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}",
)
def get_snapshot(self, project_id="", topic_id="", viewpoint_id="") -> str:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}/snapshot",
{
"project_id": project_id,
"topic_id": topic_id,
"viewpoint_id": viewpoint_id,
},
)
def get_bitmap(self, project_id="", topic_id="", viewpoint_id="", bitmap_id="") -> str:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}/bitmaps/{bitmap_id}",
{
"project_id": project_id,
"topic_id": topic_id,
"viewpoint_id": viewpoint_id,
"bitmap_id": bitmap_id,
},
)
def get_selection(self, project_id="", topic_id="", viewpoint_id="") -> dict:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}/selection",
{
"project_id": project_id,
"topic_id": topic_id,
"viewpoint_id": viewpoint_id,
},
)
def get_coloring(self, project_id="", topic_id="", viewpoint_id="") -> dict:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}/coloring",
{
"project_id": project_id,
"topic_id": topic_id,
"viewpoint_id": viewpoint_id,
},
)
def get_visibility(self, project_id="", topic_id="", viewpoint_id="") -> dict:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/viewpoints/{viewpoint_id}/visibility",
{
"project_id": project_id,
"topic_id": topic_id,
"viewpoint_id": viewpoint_id,
},
)
def get_related_topics(self, project_id="", topic_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/related_topics",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def update_related_topics(
self,
project_id="",
topic_id="",
data=None,
):
return self.put(
f"/projects/{project_id}/topics/{topic_id}/related_topics",
data=data,
)
def get_document_references(self, project_id="", topic_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/document_references",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def create_document_reference(
self,
project_id="",
topic_id="",
data=None,
):
return self.post(
f"/projects/{project_id}/topics/{topic_id}/document_references",
data=data,
)
def update_document_references(
self,
project_id="",
topic_id="",
document_reference_id="",
data=None,
):
return self.put(
f"/projects/{project_id}/topics/{topic_id}/document_references/{document_reference_id}",
data=data,
)
def get_documents(self, project_id="", topic_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/documents",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def create_document(
self,
project_id="",
topic_id="",
guid=None,
data=None,
):
headers = {
"Authorization": "Bearer " + self.foundation_client.get_access_token(),
"Content-type": "application/octet-stream",
}
response = requests.post(
f"/projects/{project_id}/topics/{topic_id}/documents",
data=data,
params={guid},
headers=headers,
)
def get_document(self, project_id="", topic_id="", document_id="") -> str:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/documents/{document_id}",
{
"project_id": project_id,
"topic_id": topic_id,
"document_id": document_id,
},
)
def get_topics_events(self, project_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/events",
{
"project_id": project_id,
},
)
def get_topic_events(self, project_id="", topic_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/events",
{
"project_id": project_id,
"topic_id": topic_id,
},
)
def get_comments_events(self, project_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/comments/events",
{
"project_id": project_id,
},
)
def get_comment_events(self, project_id="", topic_id="", comment_id="") -> list:
return self.get(
f"/projects/{project_id}/topics/{topic_id}/comments/{comment_id}/events",
{
"project_id": project_id,
"topic_id": topic_id,
"comment_id": comment_id,
},
)
+30
View File
@@ -0,0 +1,30 @@
# Server-Test
1. Cd to the server directory i.e cd `IfcOpenShell\src\bcfserver`
2. Set up the server by installing the dependencies
3. Run `pip install -r requirements.txt` to install the dependencies
4. In Python Shell, do the following
- from run import db
- db.create_all() to setup the database table
5. Run `set FLASK_APP=run.py`
6. Run `flask run` to start the server
7. Go to [http://localhost:5000](http://localhost:5000) to see the server
# Register the user
1. Go to http://localhost:5000/register to register the user
2. Create the client
3. For grant type enter authorization_code
4. For response_type enter code secret
5. Enter the scope and create the client
### You will be redirected to the page with the details of your client id and secret
# Foundation API
- Set the Base URL will be `http://127.0.0.1:5000/`
+51
View File
@@ -0,0 +1,51 @@
from flask import jsonify, url_for, redirect, render_template, request, session, flash
from flask_login import login_user, logout_user, login_required, current_user
from flask.blueprints import Blueprint
from website.models import User, OAuth2AuthorizationCode, OAuth2Token, OAuth2Client
from run import app, db
import json
bcf = Blueprint("bcf", __name__, template_folder="templates", url_prefix="/bcf/3.0")
@bcf.route("/projects")
def projects():
Headers = str.split(request.headers["Authorization"])
token = Headers[1]
access_token = OAuth2Token.query.filter_by(access_token=token).first()
print(access_token)
if access_token:
Body = {
"project_id": "F445F4F2-4D02-4B2A-B612-5E456BEF9137",
"name": "Example project 1",
"authorization": {"project_actions": ["createTopic", "createDocument"]},
}, {
"project_id": "A233FBB2-3A3B-EFF4-C123-DE22ABC8414",
"name": "Example project 2",
"authorization": {"project_actions": []},
}
response = app.response_class(
response=json.dumps(Body),
status=200,
mimetype="application/json",
)
return response
else:
message = {"error": "User not recognized"}
response = app.response_class(
response=jsonify(message),
status=200,
mimetype="application/json",
)
return response
@bcf.route("/")
@login_required
def bcf_3():
return "<h1>BCF HOMPAGE</h1>"
@bcf.route("/projects/<project_id>")
def project_details(project_id):
return "Project details"
+8
View File
@@ -0,0 +1,8 @@
Authlib==0.15.4
email-validator==1.1.3
Flask==2.0.1
Flask-Login==0.5.0
Flask-SQLAlchemy==2.5.1
Flask-WTF==0.15.1
Flask-Bcrypt==0.7.1
bcrypt==3.2.0
+25
View File
@@ -0,0 +1,25 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
app = Flask(__name__)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
bcrypt = Bcrypt(app)
app.config["SECRET_KEY"] = "f613729206685405cde0e388"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///sqlite.db"
login_manager.login_view = "website_obj.login_page"
login_manager.login_message_category = "info"
from website.routes import website_obj
from bcf.routes import bcf
app.register_blueprint(website_obj)
app.register_blueprint(bcf)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
+54
View File
@@ -0,0 +1,54 @@
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo
from wtforms import ValidationError
from .models import User
class RegisterForm(FlaskForm):
def validate_username(self, username_to_check):
user = User.query.filter_by(username=username_to_check.data).first()
if user:
raise ValidationError(
"Username already exists! Please try a different username"
)
def validate_email_address(self, email_address_to_check):
email_address = User.query.filter_by(
email_address=email_address_to_check.data
).first()
if email_address:
raise ValidationError("Email Address already exists!")
username = StringField(
label="User Name:", validators=[Length(min=2, max=30), DataRequired()]
)
email_address = StringField(
label="Email Address:", validators=[Email(), DataRequired()]
)
password1 = PasswordField(
label="Password:", validators=[Length(min=6), DataRequired()]
)
password2 = PasswordField(
label="Confirm Password:", validators=[EqualTo("password1"), DataRequired()]
)
submit = SubmitField(label="Create Account")
class LoginForm(FlaskForm):
username = StringField(label="User Name:", validators=[DataRequired()])
password = PasswordField(label="Password:", validators=[DataRequired()])
submit = SubmitField(label="Sign in")
class OauthForm(FlaskForm):
client_name = StringField(label="Client Name:", validators=[DataRequired()])
# client_uri = StringField(label="Client URI:", validators=[DataRequired()])
grant_types = StringField(label="Grant Types:", validators=[DataRequired()])
# redirect_uris = StringField(label="Redirect URIs:", validators=[DataRequired()])
response_types = StringField(label="Response Types:", validators=[DataRequired()])
scope = StringField(label="Scope:", validators=[DataRequired()])
# token_endpoint_auth_method = StringField(
# label="Token Endpoint Auth Method:", validators=[DataRequired()]
# )
submit = SubmitField(label="Create OAuth")
+69
View File
@@ -0,0 +1,69 @@
from run import db, bcrypt, login_manager
import time
from authlib.integrations.sqla_oauth2 import (
OAuth2ClientMixin,
OAuth2AuthorizationCodeMixin,
OAuth2TokenMixin,
)
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password_hash = db.Column(db.String(80), nullable=False)
email_address = db.Column(db.String(50), unique=True, nullable=False)
def __str__(self):
return f"{self.username} {self.email_address}"
def get_user_id(self):
return self.id
@property
def password(self):
return self.password
@password.setter
def password(self, plain_text_password):
self.password_hash = bcrypt.generate_password_hash(plain_text_password).decode(
"utf-8"
)
def check_password(self, attempted_password):
return bcrypt.check_password_hash(self.password_hash, attempted_password)
class OAuth2Client(db.Model, OAuth2ClientMixin):
__tablename__ = "oauth2_client"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User", lazy=True)
class OAuth2AuthorizationCode(db.Model, OAuth2AuthorizationCodeMixin):
__tablename__ = "oauth2_code"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User", lazy=True)
class OAuth2Token(db.Model, OAuth2TokenMixin):
__tablename__ = "oauth2_token"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User", lazy=True)
def is_refresh_token_active(self):
if self.revoked:
return False
expires_at = self.issued_at + self.expires_in * 2
return expires_at >= time.time()
+102
View File
@@ -0,0 +1,102 @@
from authlib.integrations.flask_oauth2 import (
AuthorizationServer,
ResourceProtector,
)
from authlib.integrations.sqla_oauth2 import (
create_query_client_func,
create_save_token_func,
create_revocation_endpoint,
create_bearer_token_validator,
)
from authlib.oauth2.rfc6749 import grants
from authlib.oauth2.rfc7636 import CodeChallenge
from .models import db, User
from .models import OAuth2Client, OAuth2AuthorizationCode, OAuth2Token
class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
TOKEN_ENDPOINT_AUTH_METHODS = [
"client_secret_basic",
"client_secret_post",
"none",
]
def save_authorization_code(self, code, request):
code_challenge = request.data.get("code_challenge")
code_challenge_method = request.data.get("code_challenge_method")
auth_code = OAuth2AuthorizationCode(
code=code,
client_id=request.client.client_id,
redirect_uri=request.redirect_uri,
scope=request.scope,
user_id=request.user.id,
code_challenge=code_challenge,
code_challenge_method=code_challenge_method,
)
db.session.add(auth_code)
db.session.commit()
return auth_code
def query_authorization_code(self, code, client):
auth_code = OAuth2AuthorizationCode.query.filter_by(
code=code, client_id=client.client_id
).first()
if auth_code and not auth_code.is_expired():
return auth_code
def delete_authorization_code(self, authorization_code):
db.session.delete(authorization_code)
db.session.commit()
def authenticate_user(self, authorization_code):
return User.query.get(authorization_code.user_id)
class PasswordGrant(grants.ResourceOwnerPasswordCredentialsGrant):
def authenticate_user(self, username, password):
user = User.query.filter_by(username=username).first()
if user is not None and user.check_password(password):
return user
class RefreshTokenGrant(grants.RefreshTokenGrant):
def authenticate_refresh_token(self, refresh_token):
token = OAuth2Token.query.filter_by(refresh_token=refresh_token).first()
if token and token.is_refresh_token_active():
return token
def authenticate_user(self, credential):
return User.query.get(credential.user_id)
def revoke_old_credential(self, credential):
credential.revoked = True
db.session.add(credential)
db.session.commit()
query_client = create_query_client_func(db.session, OAuth2Client)
save_token = create_save_token_func(db.session, OAuth2Token)
authorization = AuthorizationServer(
query_client=query_client,
save_token=save_token,
)
require_oauth = ResourceProtector()
def config_oauth(app):
authorization.init_app(app)
# support all grants
authorization.register_grant(grants.ImplicitGrant)
authorization.register_grant(grants.ClientCredentialsGrant)
authorization.register_grant(AuthorizationCodeGrant, [CodeChallenge(required=True)])
authorization.register_grant(PasswordGrant)
authorization.register_grant(RefreshTokenGrant)
# support revocation
revocation_cls = create_revocation_endpoint(db.session, OAuth2Token)
authorization.register_endpoint(revocation_cls)
# protect resource
bearer_cls = create_bearer_token_validator(db.session, OAuth2Token)
require_oauth.register_token_validator(bearer_cls())
+302
View File
@@ -0,0 +1,302 @@
from flask.blueprints import Blueprint
from flask import render_template, redirect, url_for, flash, request
from werkzeug import datastructures
from .forms import RegisterForm, LoginForm, OauthForm
from flask_login import login_user, logout_user, login_required, current_user
from .models import User, OAuth2Client, OAuth2AuthorizationCode, OAuth2Token
import base64
from werkzeug.security import gen_salt
import time
import urllib
import json
from run import db, app
website_obj = Blueprint(
"website_obj",
__name__,
template_folder="templates",
)
def split_by_crlf(s):
return [v for v in s.splitlines() if v]
@website_obj.route("/")
def homepage():
return render_template("index.html")
# return "homepage"
@website_obj.route("/register", methods=["GET", "POST"])
def register_page():
form = RegisterForm()
if form.validate_on_submit():
user_to_create = User(
username=form.username.data,
email_address=form.email_address.data,
password=form.password1.data,
)
db.session.add(user_to_create)
db.session.commit()
login_user(user_to_create)
flash(
f"Account created successfully! {user_to_create.username}",
category="success",
)
return redirect(url_for("website_obj.homepage"))
if form.errors != {}:
for err_msg in form.errors.values():
flash(
f"There was an error with creating a user: {err_msg}", category="danger"
)
return render_template("register.html", form=form)
@website_obj.route("/createclient", methods=["GET", "POST"])
@login_required
def create_client():
grants = [
"AuthorizationCodeGrant",
"ImplicitGrant",
"ResourceOwnerPasswordCredentialsGrant",
"ClientCredentialsGrant",
"RefreshTokenGrant",
]
form = OauthForm()
if form.validate_on_submit():
client_id = gen_salt(24)
client_id_issued_at = int(time.time())
client = OAuth2Client(
client_id=client_id,
client_id_issued_at=client_id_issued_at,
user_id=current_user.id,
)
client_metadata = {
"client_name": form.client_name.data,
"grant_types": split_by_crlf(form.grant_types.data),
"response_types": split_by_crlf(form.response_types.data),
"scope": form.scope.data,
"token_endpoint_auth_method": "client_secret_basic",
}
client.client_secret = gen_salt(48)
client.set_client_metadata(client_metadata)
db.session.add(client)
db.session.commit()
flash(
"Oauth Client Created Successfully",
category="info",
)
clients = OAuth2Client.query.filter_by(user_id=current_user.id).all()
for client in clients:
print(client.client_info)
print(client.client_metadata)
return render_template("clientdata.html", user=current_user.id, clients=clients)
return render_template("createclient.html", form=form, grants=grants)
@website_obj.route("/login", methods=["GET", "POST"])
def login_page():
form = LoginForm()
if form.validate_on_submit():
attempted_user = User.query.filter_by(username=form.username.data).first()
if attempted_user and attempted_user.check_password(
attempted_password=form.password.data
):
login_user(attempted_user)
return redirect(url_for("website_obj.homepage"))
else:
flash(
"Invalid Credentials",
category="danger",
)
return render_template("login.html", form=form)
@website_obj.route("/logout")
def logoutpage():
logout_user()
flash("You have been logged out!", category="info")
return redirect(url_for("website_obj.homepage"))
@website_obj.route("/foundation/1.0/auth")
def foundation_auth():
data = {
"oauth2_auth_url": "http://127.0.0.1:5000/oauth/authorize",
"oauth2_token_url": "http://127.0.0.1:5000/oauth/token",
"supported_oauth2_flows": ["authorization_code"],
}
response = app.response_class(
response=json.dumps(data), status=200, mimetype="application/json"
)
return response
@website_obj.route("/foundation/versions")
def foundation_versions():
Body = {
"versions": [
{
"api_id": "opencde-foundation",
"version_id": "1.0",
"detailed_version": "https://github.com/BuildingSMART/opencde-foundation-API/tree/v1.0",
},
# {
# "api_id": "bcf",
# "version_id": "2.1",
# "detailed_version": "https://github.com/buildingSMART/BCF-API/tree/release_2_1",
# "api_base_url": "http://127.0.0.1:5000/bcf/2.1"
# },
{
"api_id": "bcf",
"version_id": "3.0",
"detailed_version": "https://github.com/buildingSMART/BCF-API/tree/release_3_0",
"api_base_url": "http://127.0.0.1:5000/bcf/3.0",
},
]
}
response = app.response_class(
response=json.dumps(Body), status=200, mimetype="application/json"
)
return response
@website_obj.route("/outh/login", methods=["GET", "POST"])
def oauth_login():
form = LoginForm()
if form.validate_on_submit():
attempted_user = User.query.filter_by(username=form.username.data).first()
if attempted_user and attempted_user.check_password(
attempted_password=form.password.data
):
login_user(attempted_user)
flash(
"Invalid Credentials",
category="info",
)
client_id = request.args.get("client_id")
redirect_uri = request.args.get("redirect_uri")
state = request.args.get("state")
return redirect(
url_for(
"website_obj.authorize",
client_id=client_id,
redirect_uri=redirect_uri,
state=state,
)
)
else:
flash(
"Invalid Credentials",
category="danger",
)
return render_template("ologin.html", form=form)
@website_obj.route("/oauth/authorize", methods=["GET", "POST"])
def authorize():
client_id = request.args.get("client_id")
redirect_uri = request.args.get("redirect_uri")
state = request.args.get("state")
if current_user.is_anonymous:
flash("Please Login !", category="info")
query = request.query_string
return redirect(
url_for(
"website_obj.oauth_login",
client_id=client_id,
redirect_uri=redirect_uri,
state=state,
)
)
else:
try:
user = current_user.id
flash(message=redirect_uri, category="warning")
client = OAuth2Client.query.filter_by(client_id=client_id).first()
if client:
if client.user_id == user:
code = gen_salt(48)
OauthCode = OAuth2AuthorizationCode(
client_id=client_id,
redirect_uri=redirect_uri,
user_id=user,
code=code,
response_type="code",
)
db.session.add(OauthCode)
db.session.commit()
query = urllib.parse.urlencode(
{
"code": OauthCode.code,
"state": state,
}
)
return redirect(f"{redirect_uri}?{query}")
else:
flash(
"You are not authorized to access this client",
category="danger",
)
else:
flash("Client not found", category="danger")
except Exception as e:
flash(e, category="danger")
return render_template("oauth.html")
@website_obj.route("/oauth/token", methods=["POST"])
def issue_token():
try:
code = request.form["code"]
Headers = str.split(request.headers["Authorization"])
decode_header = base64.b64decode(Headers[1]).decode("utf-8")
creds = decode_header.split(":")
client_id = creds[0]
# print(code, Headers, decode_header, creds, client_id)
auth_code = OAuth2AuthorizationCode.query.filter_by(code=code).first()
if auth_code:
if auth_code.client_id == client_id:
access_token = gen_salt(48)
refresh_token = gen_salt(48)
expires_in = 3600
OauthToken = OAuth2Token(
client_id=auth_code.client_id,
user_id=auth_code.user_id,
access_token=access_token,
refresh_token=refresh_token,
expires_in=expires_in,
scope=auth_code.scope,
token_type="Bearer",
)
db.session.add(OauthToken)
db.session.commit()
query = {
"access_token": access_token,
"refresh_token": refresh_token,
"expires_in": expires_in,
}
response = app.response_class(
response=json.dumps(query),
status=200,
mimetype="application/json",
)
print(query)
return response
else:
flash(
"You are not authorized to access this client",
category="danger",
)
else:
flash("Client not found", category="danger")
except Exception as e:
flash(e, category="danger")
return render_template("oauth.html")
+115
View File
@@ -0,0 +1,115 @@
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous"
/>
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<a class="navbar-brand" href="#">BCF OLD SERVER</a>
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{{ url_for('website_obj.homepage') }}"
>Home <span class="sr-only">(current)</span></a
>
</li>
</ul>
{% if current_user.is_authenticated %}
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" style="color: lawngreen; font-weight: bold">
<i class="fas fa-coins"></i>
{{ current_user.prettier_budget }}
</a>
</li>
<li class="nav-item">
<a class="nav-link">Welcome, {{ current_user.username }}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('website_obj.logoutpage') }}"
>Logout</a
>
</li>
<li class="nav-item">
<a
class="nav-link"
href="{{ url_for('website_obj.create_client') }}"
>Create Client</a
>
</li>
</ul>
{% else %}
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{ url_for('website_obj.login_page') }}"
>Login</a
>
</li>
<li class="nav-item">
<a
class="nav-link"
href="{{ url_for('website_obj.register_page') }}"
>Register</a
>
</li>
</ul>
{% endif %}
</div>
</nav>
{% with messages = get_flashed_messages(with_categories=true) %} {% if
messages %} {% for category, message in messages %}
<div class="alert alert-{{ category }}">
<button
type="button"
class="m1-2 mb-1 close"
data-dismiss="alert"
aria-label="Close"
>
<span aria-hidden="true">&times;</span>
</button>
{{ message }}
</div>
{% endfor %} {% endif %} {% endwith %} {% block content %} {% endblock %}
<!-- Future Content here -->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"
></script>
</body>
</html>
@@ -0,0 +1,17 @@
{%extends 'base.html'%} {%block content%} {% if user %}
<style>
pre {
white-space: wrap;
}
</style>
<div>Logged in as <strong>{{user}}</strong></div>
{% for client in clients %}
<pre>
{{ client.client_info|tojson }}
{{ client.client_metadata|tojson }}
</pre>
<hr />
{% endfor %} {% else %}
<div>Not logged in</div>
{% endif %} {% endblock %}
@@ -0,0 +1,28 @@
{%extends 'base.html' %} {%block title %} {% endblock%} {%block content%}
<body class="text-center">
<div class="container">
<form method="post" class="form-register" style="color: black">
{{form.hidden_tag()}}
<h1 class="h3 mb-3 font-weight-normal font-monospace text-center">
Register
</h1>
{{form.client_name.label()}} {{form.client_name(class="form-control",
placeholder="Client_name")}}
<!-- <label for="grant_types">Select grant Type</label>
<select name="grants">
{% for grant in grants%}
<option value="{{ grant_types}}" selected>{{ grant }}</option>
{% endfor %}
</select> -->
{{form.grant_types.label()}} {{form.grant_types(class="form-control",
placeholder="Grant_Types")}} {{form.response_types.label()}}
{{form.response_types(class="form-control",
placeholder="Response_Types")}} {{form.scope.label()}}
{{form.scope(class="form-control", placeholder="Scope")}}
<br />
{{form.submit(class="btn btn-lg btn-primary btn-block" ,value="Create
Oauth Credentials")}}
</form>
</div>
</body>
{% endblock %}
@@ -0,0 +1,16 @@
<!-- {%extends 'base.html'%} {%block title%} Homepage {%endblock%} {%block content%}
<h1>BCF Open Source Server Homepage</h1>
{%endblock%} -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
Home Page
</body>
</html>
@@ -0,0 +1,27 @@
{% extends 'base.html' %} {% block title %}{% endblock %} {% block content %}
<body class="text-center">
<div class="container">
<form method="POST" class="form-signin" style="color: black">
{{ form.hidden_tag() }}
<h1 class="h3 mb-3 font-weight-normal">Please Login</h1>
<br />
{{ form.username.label() }} {{ form.username(class="form-control",
placeholder="User Name") }} {{ form.password.label() }} {{
form.password(class="form-control", placeholder="Password") }}
<br />
<div class="checkbox mb-3">
<h6>Do not have an account?</h6>
<a
class="btn btn-sm btn-secondary"
href="{{ url_for('website_obj.register_page') }}"
>Register</a
>
</div>
{{ form.submit(class="btn btn-lg btn-block btn-primary") }}
</form>
</div>
</body>
{% endblock %}
@@ -0,0 +1 @@
{%extends "base.html"%} {%block content%} this is Oauth page {%endblock%}
@@ -0,0 +1,28 @@
{% extends 'base.html' %} {% block title %}{% endblock %} {% block content %}
<body class="text-center">
<div class="container">
<form method="POST" class="form-signin" style="color: black">
{{ form.hidden_tag() }}
<h1 class="h3 mb-3 font-weight-normal">Please Login</h1>
THis is Oauth Login
<br />
{{ form.username.label() }} {{ form.username(class="form-control",
placeholder="User Name") }} {{ form.password.label() }} {{
form.password(class="form-control", placeholder="Password") }}
<br />
<div class="checkbox mb-3">
<h6>Do not have an account?</h6>
<a
class="btn btn-sm btn-secondary"
href="{{ url_for('website_obj.register_page') }}"
>Register</a
>
</div>
{{ form.submit(class="btn btn-lg btn-block btn-primary") }}
</form>
</div>
</body>
{% endblock %}
@@ -0,0 +1,30 @@
{%extends 'base.html' %} {%block title %} {% endblock%} {%block content%}
<body class="text-center">
<div class="container">
<form method="post" class="form-register" style="color: black">
{{form.hidden_tag()}}
<h1 class="h3 mb-3 font-weight-normal font-monospace text-center">
Register
</h1>
{{form.username.label()}} {{form.username(class="form-control"
,placeholder="Username")}} {{form.email_address.label()}}
{{form.email_address(class="form-control" ,placeholder="Email Address")}}
{{form.password1.label()}}
{{form.password1(class="form-control",placeholder="Password")}}
{{form.password2.label()}} {{form.password2(class="form-control"
,placeholder="Confirm Password")}}
<br />
<div class="checkbox mb-3">
<h6>Already have an account?</h6>
<a
class="btn btn-sm btn-secondary"
href="{{ url_for('website_obj.login_page') }}"
>Login</a
>
</div>
{{form.submit(class="btn btn-lg btn-primary btn-block"
,value="Register")}}
</form>
</div>
</body>
{% endblock %}
+621
View File
@@ -0,0 +1,621 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
+153 -20
View File
@@ -1,6 +1,63 @@
VERSION:=`date '+%y%m%d'`
PYVERSION:=py37
ifeq ($(PYVERSION), py37)
PYLIBDIR:=python3.7
PYNUMBER:=37
endif
ifeq ($(PYVERSION), py39)
PYLIBDIR:=python3.9
PYNUMBER:=39
endif
ifeq ($(PLATFORM), linux)
ifeq ($(PYVERSION), py37)
HPPFCL_URL:=https://anaconda.org/conda-forge/hpp-fcl/1.7.5/download/linux-64/hpp-fcl-1.7.5-py37h5f1835d_0.tar.bz2
EIGENPY_URL:=https://anaconda.org/conda-forge/eigenpy/2.6.5/download/linux-64/eigenpy-2.6.5-py37h95e2c48_0.tar.bz2
BOOST_URL:=https://anaconda.org/conda-forge/boost/1.74.0/download/linux-64/boost-1.74.0-py37h0379df6_3.tar.bz2
endif
ifeq ($(PYVERSION), py39)
HPPFCL_URL:=https://anaconda.org/conda-forge/hpp-fcl/1.7.5/download/linux-64/hpp-fcl-1.7.5-py39hbcdfc36_0.tar.bz2
EIGENPY_URL:=https://anaconda.org/conda-forge/eigenpy/2.6.5/download/linux-64/eigenpy-2.6.5-py39h5aed9d1_0.tar.bz2
BOOST_URL:=https://anaconda.org/conda-forge/boost/1.74.0/download/linux-64/boost-1.74.0-py39h5472131_3.tar.bz2
endif
ASSIMP_URL:=https://anaconda.org/conda-forge/assimp/5.0.1/download/linux-64/assimp-5.0.1-hedfc422_6.tar.bz2
OCTOMAP_URL:=https://anaconda.org/conda-forge/octomap/1.9.7/download/linux-64/octomap-1.9.7-h4bd325d_0.tar.bz2
ZLIB_URL:=https://anaconda.org/conda-forge/zlib/1.2.11/download/linux-64/zlib-1.2.11-h516909a_1010.tar.bz2
endif
ifeq ($(PLATFORM), macos)
ifeq ($(PYVERSION), py37)
HPPFCL_URL:=https://anaconda.org/conda-forge/hpp-fcl/1.7.5/download/osx-64/hpp-fcl-1.7.5-py37h2d7f23a_0.tar.bz2
EIGENPY_URL:=https://anaconda.org/conda-forge/eigenpy/2.6.5/download/osx-64/eigenpy-2.6.5-py37h0695097_0.tar.bz2
BOOST_URL:=https://anaconda.org/conda-forge/boost/1.74.0/download/osx-64/boost-1.74.0-py37hd79e0ac_3.tar.bz2
endif
ifeq ($(PYVERSION), py39)
HPPFCL_URL:=https://anaconda.org/conda-forge/hpp-fcl/1.7.5/download/osx-64/hpp-fcl-1.7.5-py39h1e32b98_0.tar.bz2
EIGENPY_URL:=https://anaconda.org/conda-forge/eigenpy/2.6.5/download/osx-64/eigenpy-2.6.5-py39h5405915_0.tar.bz2
BOOST_URL:=https://anaconda.org/conda-forge/boost/1.74.0/download/osx-64/boost-1.74.0-py39ha641261_3.tar.bz2
endif
ASSIMP_URL:=https://anaconda.org/conda-forge/assimp/5.0.1/download/osx-64/assimp-5.0.1-h1224e73_6.tar.bz2
OCTOMAP_URL:=https://anaconda.org/conda-forge/octomap/1.9.7/download/osx-64/octomap-1.9.7-h940c156_0.tar.bz2
ZLIB_URL:=https://anaconda.org/conda-forge/zlib/1.2.11/download/osx-64/zlib-1.2.11-h7795811_1010.tar.bz2
endif
ifeq ($(PLATFORM), win)
ifeq ($(PYVERSION), py37)
HPPFCL_URL:=https://anaconda.org/conda-forge/hpp-fcl/1.7.5/download/win-64/hpp-fcl-1.7.5-py37h839d6b1_0.tar.bz2
EIGENPY_URL:=https://anaconda.org/conda-forge/eigenpy/2.6.5/download/win-64/eigenpy-2.6.5-py37h2c32e34_0.tar.bz2
BOOST_URL:=https://anaconda.org/conda-forge/boost/1.74.0/download/win-64/boost-1.74.0-py37h3b38789_3.tar.bz2
endif
ifeq ($(PYVERSION), py39)
HPPFCL_URL:=https://anaconda.org/conda-forge/hpp-fcl/1.7.5/download/win-64/hpp-fcl-1.7.5-py39h2e7c763_0.tar.bz2
EIGENPY_URL:=https://anaconda.org/conda-forge/eigenpy/2.6.5/download/win-64/eigenpy-2.6.5-py39h3ce40e6_0.tar.bz2
BOOST_URL:=https://anaconda.org/conda-forge/boost/1.74.0/download/win-64/boost-1.74.0-py39hefe7e4c_3.tar.bz2
endif
ASSIMP_URL:=https://anaconda.org/conda-forge/assimp/5.0.1/download/win-64/assimp-5.0.1-hc2aa0de_6.tar.bz2
OCTOMAP_URL:=https://anaconda.org/conda-forge/octomap/1.9.7/download/win-64/octomap-1.9.7-h5362a0b_0.tar.bz2
ZLIB_URL:=https://anaconda.org/conda-forge/zlib/1.2.11/download/win-64/zlib-1.2.11-h62dcd97_1010.tar.bz2
endif
.PHONY: dist
dist:
ifndef PLATFORM
@@ -12,12 +69,7 @@ endif
cp -r blenderbim/* dist/blenderbim/
# Provides IfcOpenShell Python functionality
ifeq ($(PYVERSION), py37)
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-37-v0.6.0-2fd2b49-$(PLATFORM)64.zip
endif
ifeq ($(PYVERSION), py39)
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-39-v0.6.0-2fd2b49-$(PLATFORM)64.zip
endif
cd dist/working && wget https://s3.amazonaws.com/ifcopenshell-builds/ifcblender-python-$(PYNUMBER)-v0.6.0-0087fa8-$(PLATFORM)64.zip
cd dist/working && unzip ifcblender*
cp -r dist/working/io_import_scene_ifc/ifcopenshell dist/blenderbim/libs/site/packages/
@@ -44,10 +96,12 @@ endif
# IfcOpenBot sometimes lags behind, so we hotfix the Python utilities
cp -r dist/working/IfcOpenShell-0.6.0/src/ifcopenshell-python/ifcopenshell/util/* dist/blenderbim/libs/site/packages/ifcopenshell/util/
cp -r dist/working/IfcOpenShell-0.6.0/src/ifcopenshell-python/ifcopenshell/api/* dist/blenderbim/libs/site/packages/ifcopenshell/api/
cp dist/working/IfcOpenShell-0.6.0/src/ifcopenshell-python/ifcopenshell/entity_instance.py dist/blenderbim/libs/site/packages/ifcopenshell/
cp dist/working/IfcOpenShell-0.6.0/src/ifcopenshell-python/ifcopenshell/file.py dist/blenderbim/libs/site/packages/ifcopenshell/
# Provides bcf functionality
cp -r dist/working/IfcOpenShell-0.6.0/src/bcf/bcf dist/blenderbim/libs/site/packages/
# Provides IFCClash functionality
cp -r dist/working/IfcOpenShell-0.6.0/src/ifcclash/* dist/blenderbim/libs/site/packages/
cp -r dist/working/IfcOpenShell-0.6.0/src/ifcclash/ifcclash dist/blenderbim/libs/site/packages/
# Provides BIMTester functionality
cd dist/working && python -m venv env
cd dist/working && . env/bin/activate && pip install pybabel
@@ -62,8 +116,10 @@ endif
cp -r dist/working/IfcOpenShell-0.6.0/src/ifccsv/* dist/blenderbim/libs/site/packages/
# Provides IFCPatch functionality
cp -r dist/working/IfcOpenShell-0.6.0/src/ifcpatch/ifcpatch dist/blenderbim/libs/site/packages/
# Provides IFCP6 functionality
cp -r dist/working/IfcOpenShell-0.6.0/src/ifcp6/ifcp6 dist/blenderbim/libs/site/packages/
# Provides IFC4D functionality
cp -r dist/working/IfcOpenShell-0.6.0/src/ifc4d/ifc4d dist/blenderbim/libs/site/packages/
# Provides IFC5D functionality
cp -r dist/working/IfcOpenShell-0.6.0/src/ifc5d/ifc5d dist/blenderbim/libs/site/packages/
rm -rf dist/working
# Provides Mustache templating in construction documentation
@@ -172,20 +228,97 @@ endif
rm -rf dist/working
# Required by IFCClash
ifeq ($(PLATFORM), linux)
mkdir dist/working
cd dist/working && wget https://files.pythonhosted.org/packages/0c/fa/00d85f893b02289e2942849d97f8818dde8e2111182e825fb3a735677791/python_fcl-0.0.12-cp37-cp37m-manylinux1_x86_64.whl
cd dist/working && unzip python_fcl*
cp -r dist/working/fcl dist/blenderbim/libs/site/packages/
rm -rf dist/working
cd dist/working && wget $(HPPFCL_URL)
cd dist/working && tar -xf hpp-fcl*
ifeq ($(PLATFORM), linux)
cp -r dist/working/lib/$(PYLIBDIR)/site-packages/hppfcl dist/blenderbim/libs/site/packages/
cp -r dist/working/lib/*.so* dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), macos)
cp -r dist/working/lib/$(PYLIBDIR)/site-packages/hppfcl dist/blenderbim/libs/site/packages/
cp -r dist/working/lib/*.dylib dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), win)
mkdir dist/working
cd dist/working && wget https://files.pythonhosted.org/packages/19/e6/6e9f33fb59e8f27c0e1592bd26e644bc92b85c942b072b2d3854105d5887/python_fcl_win32-0.0.12.post3-py3-none-win_amd64.whl
cd dist/working && unzip python_fcl*
cp -r dist/working/fcl dist/blenderbim/libs/site/packages/
rm -rf dist/working
cp -r dist/working/Lib/site-packages/hppfcl dist/blenderbim/libs/site/packages/
cp -r dist/working/Library/bin/*.dll dist/blenderbim/libs/site/packages/hppfcl/
endif
rm -rf dist/working
# Required by hpp-fcl
mkdir dist/working
cd dist/working && wget $(ASSIMP_URL)
cd dist/working && tar -xf assimp*
ifeq ($(PLATFORM), linux)
cp -r dist/working/lib/*.so* dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), macos)
cp -r dist/working/lib/*.dylib dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), win)
cp -r dist/working/Library/bin/*.dll dist/blenderbim/libs/site/packages/hppfcl/
endif
rm -rf dist/working
# Required by hpp-fcl
mkdir dist/working
cd dist/working && wget $(EIGENPY_URL)
cd dist/working && tar -xf eigenpy*
ifeq ($(PLATFORM), linux)
cp -r dist/working/lib/*.so* dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), macos)
cp -r dist/working/lib/*.dylib dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), win)
cp -r dist/working/Library/bin/*.dll dist/blenderbim/libs/site/packages/hppfcl/
endif
rm -rf dist/working
# Required by hpp-fcl
mkdir dist/working
cd dist/working && wget $(OCTOMAP_URL)
cd dist/working && tar -xf octomap*
ifeq ($(PLATFORM), linux)
cp -r dist/working/lib/*.so* dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), macos)
cp -r dist/working/lib/*.dylib dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), win)
# Uh, do nothing, apparently? No DLLs are shipped.
endif
rm -rf dist/working
# Required by hpp-fcl
mkdir dist/working
cd dist/working && wget $(BOOST_URL)
cd dist/working && tar -xf boost*
ifeq ($(PLATFORM), linux)
cp -r dist/working/lib/*.so* dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), macos)
cp -r dist/working/lib/*.dylib dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), win)
cp -r dist/working/Library/bin/*.dll dist/blenderbim/libs/site/packages/hppfcl/
endif
rm -rf dist/working
# Required by hpp-fcl
mkdir dist/working
cd dist/working && wget $(ZLIB_URL)
cd dist/working && tar -xf zlib*
ifeq ($(PLATFORM), linux)
cp -r dist/working/lib/*.so* dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), macos)
cp -r dist/working/lib/*.dylib dist/blenderbim/libs/
endif
ifeq ($(PLATFORM), win)
cp -r dist/working/Library/bin/*.dll dist/blenderbim/libs/site/packages/hppfcl/
endif
rm -rf dist/working
# Required by BIMTester
mkdir dist/working
@@ -270,7 +403,7 @@ endif
rm -rf dist/working
cd dist/blenderbim && sed -i "s/999999/$(VERSION)/" __init__.py
cd dist && zip -r blender28-bim-$(VERSION)-$(PYVERSION)-$(PLATFORM).zip ./*
cd dist && zip -r blenderbim-$(VERSION)-$(PYVERSION)-$(PLATFORM).zip ./*
rm -rf dist/blenderbim
.PHONY: clean
@@ -29,8 +29,10 @@ if bpy is not None:
"cost": None,
"sequence": None,
"group": None,
"system": None,
"structural": None,
"boundary": None,
"profile": None,
"material": None,
"style": None,
"layer": None,
+10 -8
View File
@@ -5,12 +5,11 @@ import numpy as np
import datetime
import zipfile
import tempfile
import ifcopenshell
import ifcopenshell.util.placement
import ifcopenshell.api
from ifcopenshell.api.spatial.data import Data as SpatialData
from blenderbim.bim.ifc import IfcStore
import addon_utils
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.util.placement
from blenderbim.bim.ifc import IfcStore
class IfcExporter:
@@ -68,6 +67,8 @@ class IfcExporter:
for ifc_definition_id, obj in IfcStore.id_map.items():
try:
if isinstance(obj, bpy.types.Material):
continue
self.sync_object_placement(obj)
self.sync_object_container(ifc_definition_id, obj)
except ReferenceError:
@@ -75,8 +76,6 @@ class IfcExporter:
if self.should_delete(obj):
to_delete.append(ifc_definition_id)
SpatialData.purge()
for ifc_definition_id in to_delete:
product = self.file.by_id(ifc_definition_id)
IfcStore.unlink_element(product)
@@ -87,7 +86,10 @@ class IfcExporter:
if not obj:
continue
try:
bpy.ops.bim.update_representation(obj=obj.name)
if isinstance(obj, bpy.types.Material):
bpy.ops.bim.update_style_colours(material=obj.name)
else:
bpy.ops.bim.update_representation(obj=obj.name)
except ReferenceError:
pass # The object is likely deleted
IfcStore.edited_objs.clear()
+15 -5
View File
@@ -4,8 +4,10 @@ import addon_utils
import ifcopenshell.api.owner.settings
from bpy.app.handlers import persistent
from blenderbim.bim.ifc import IfcStore
from blenderbim.bim.module.owner.prop import getPersons, getOrganisations
from ifcopenshell.api.attribute.data import Data as AttributeData
from ifcopenshell.api.material.data import Data as MaterialData
from ifcopenshell.api.style.data import Data as StyleData
from ifcopenshell.api.type.data import Data as TypeData
@@ -13,6 +15,8 @@ global_subscription_owner = object()
def mode_callback(obj, data):
if not bpy.context.scene.BIMProjectProperties.is_authoring:
return
objects = bpy.context.selected_objects
if bpy.context.active_object:
objects += [bpy.context.active_object]
@@ -22,9 +26,8 @@ def mode_callback(obj, data):
or not obj.data
or not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve, bpy.types.TextCurve))
or not obj.BIMObjectProperties.ifc_definition_id
or not bpy.context.scene.BIMProjectProperties.is_authoring
):
return
continue
if obj.data.BIMMeshProperties.ifc_definition_id:
representation = IfcStore.get_file().by_id(obj.data.BIMMeshProperties.ifc_definition_id)
if representation.RepresentationType in ["Tessellation", "Brep", "Annotation2D"]:
@@ -34,6 +37,7 @@ def mode_callback(obj, data):
def name_callback(obj, data):
# TODO Do we still need this, now that we are monitoring the undo redo objects?
try:
obj.name
except:
@@ -49,6 +53,7 @@ def name_callback(obj, data):
MaterialData.load_materials()
if obj.BIMMaterialProperties.ifc_style_id:
IfcStore.get_file().by_id(obj.BIMMaterialProperties.ifc_style_id).Name = obj.name
StyleData.load(IfcStore.get_file(), obj.BIMMaterialProperties.ifc_style_id)
return
if not obj.BIMObjectProperties.ifc_definition_id or "/" not in obj.name:
@@ -75,6 +80,11 @@ def name_callback(obj, data):
AttributeData.load(IfcStore.get_file(), obj.BIMObjectProperties.ifc_definition_id)
def color_callback(obj, data):
if obj.BIMMaterialProperties.ifc_style_id:
IfcStore.edited_objs.add(obj)
def active_object_callback():
obj = bpy.context.active_object
for obj in bpy.context.selected_objects:
@@ -122,12 +132,12 @@ def purge_module_data():
@persistent
def loadIfcStore(scene):
IfcStore.purge()
purge_module_data()
ifc_file = IfcStore.get_file()
if not ifc_file:
return
IfcStore.get_schema()
IfcStore.reload_linked_elements()
purge_module_data()
@persistent
@@ -202,12 +212,12 @@ def setDefaultProperties(scene):
)
ifcopenshell.api.owner.settings.get_person = (
lambda ifc: ifc.by_id(int(bpy.context.scene.BIMOwnerProperties.user_person))
if bpy.context.scene.BIMOwnerProperties.user_person
if getPersons(None, bpy.context) and bpy.context.scene.BIMOwnerProperties.user_person
else None
)
ifcopenshell.api.owner.settings.get_organisation = (
lambda ifc: ifc.by_id(int(bpy.context.scene.BIMOwnerProperties.user_organisation))
if bpy.context.scene.BIMOwnerProperties.user_organisation
if getOrganisations(None, bpy.context) and bpy.context.scene.BIMOwnerProperties.user_organisation
else None
)
ifcopenshell.api.owner.settings.get_application = get_application
+20 -3
View File
@@ -79,15 +79,18 @@ class IfcStore:
in a regular Python list, there is the likely probability that the object
will be invalidated when undo or redo occurs. Object invalidation seems to
only occur for selected objects either pre/post undo/redo event, including
selected objects for consecutive undo/redos.
selected objects for consecutive undo/redos, and all children.
So if I first select o1, then o2, then o3, then press undo, o3 will be
invalidated. If instead I press undo twice, o3 and o2 will be invalidated.
"""
if bpy.context.active_object:
objects = set([o.name for o in bpy.context.selected_objects + [bpy.context.active_object]])
objects.update([o.name for o in bpy.context.active_object.children])
else:
objects = set([o.name for o in bpy.context.selected_objects])
for obj in bpy.context.selected_objects:
objects.update([o.name for o in obj.children])
IfcStore.undo_redo_stack_objects |= objects
@staticmethod
@@ -114,9 +117,19 @@ class IfcStore:
IfcStore.id_map[element.id()] = obj
if hasattr(element, "GlobalId"):
IfcStore.guid_map[element.GlobalId] = obj
obj.BIMObjectProperties.ifc_definition_id = element.id()
blenderbim.bim.handler.subscribe_to(obj, "mode", blenderbim.bim.handler.mode_callback)
if element.is_a("IfcSurfaceStyle"):
obj.BIMMaterialProperties.ifc_style_id = element.id()
else:
obj.BIMObjectProperties.ifc_definition_id = element.id()
blenderbim.bim.handler.subscribe_to(obj, "name", blenderbim.bim.handler.name_callback)
if isinstance(obj, bpy.types.Material):
blenderbim.bim.handler.subscribe_to(obj, "diffuse_color", blenderbim.bim.handler.color_callback)
elif isinstance(obj, bpy.types.Object):
blenderbim.bim.handler.subscribe_to(obj, "mode", blenderbim.bim.handler.mode_callback)
for listener in IfcStore.element_listeners:
listener(element, obj)
@@ -140,6 +153,10 @@ class IfcStore:
IfcStore.guid_map[data["guid"]] = obj
blenderbim.bim.handler.subscribe_to(obj, "mode", blenderbim.bim.handler.mode_callback)
blenderbim.bim.handler.subscribe_to(obj, "name", blenderbim.bim.handler.name_callback)
if isinstance(obj, bpy.types.Material):
blenderbim.bim.handler.subscribe_to(obj, "diffuse_color", blenderbim.bim.handler.color_callback)
# TODO Listeners are not re-registered. Does this cause nasty problems to debug later on?
# TODO We're handling id_map and guid_map, but what about edited_objs? This might cause big problems.
@staticmethod
def unlink_element(element=None, obj=None):
+94 -23
View File
@@ -54,9 +54,28 @@ class MaterialCreator:
if not self.mesh or self.mesh.name in self.parsed_meshes:
return
self.parsed_meshes.add(self.mesh.name)
self.add_default_material(element)
if self.parse_representations(element):
self.assign_material_slots_to_faces()
def add_default_material(self, element):
element_material = ifcopenshell.util.element.get_material(element)
if not element_material:
return
for material in [m for m in self.ifc_importer.file.traverse(element_material) if m.is_a("IfcMaterial")]:
if not material.HasRepresentation:
continue
surface_style = [
s for s in self.ifc_importer.file.traverse(material.HasRepresentation[0]) if s.is_a("IfcSurfaceStyle")
]
if surface_style:
self.mesh.materials.append(self.styles[surface_style[0].id()])
return
# For authoring convenience, we choose to assign a material, even if it has no surface style. See #1585.
for material in [m for m in self.ifc_importer.file.traverse(element_material) if m.is_a("IfcMaterial")]:
self.mesh.materials.append(self.materials[material.id()])
return
def load_existing_materials(self):
for material in bpy.data.materials:
if material.BIMObjectProperties.ifc_definition_id:
@@ -134,12 +153,12 @@ class IfcImporter:
self.settings_native.set(self.settings_native.INCLUDE_CURVES, True)
self.settings_2d = ifcopenshell.geom.settings()
self.settings_2d.set(self.settings_2d.INCLUDE_CURVES, True)
self.filter_mode = "BLACKLIST"
self.filter_mode = None
self.include_elements = set()
self.exclude_elements = set()
self.project = None
self.spatial_structure_elements = {}
self.elements = {}
self.elements = []
self.type_collection = None
self.type_products = {}
self.openings = {}
@@ -159,8 +178,16 @@ class IfcImporter:
self.time = time.time()
print("{} :: {:.2f}".format(message, time.time() - self.time))
self.time = time.time()
self.update_progress(self.progress + 1)
def update_progress(self, progress):
if progress <= 100:
self.progress = progress
bpy.context.window_manager.progress_update(self.progress)
def execute(self):
bpy.context.window_manager.progress_begin(0, 100)
self.progress = 0
self.profile_code("Starting import process")
self.load_diff()
self.profile_code("Load diff")
@@ -200,7 +227,7 @@ class IfcImporter:
self.profile_code("Create native products")
self.create_products()
self.profile_code("Create products")
self.create_empty_products()
self.create_empty_and_2d_elements()
self.profile_code("Create empty products")
self.create_type_products()
self.profile_code("Create type products")
@@ -228,6 +255,8 @@ class IfcImporter:
self.profile_code("Mesh cleaning")
self.set_default_context()
self.profile_code("Setting default context")
self.update_progress(100)
bpy.context.window_manager.progress_end()
def is_element_far_away(self, element, is_meters=True):
try:
@@ -320,12 +349,15 @@ class IfcImporter:
props = bpy.context.scene.BIMGeoreferenceProperties
if props.has_blender_offset:
return
project = self.file.by_type("IfcProject")[0]
if self.file.schema == "IFC2X3":
project = self.file.by_type("IfcProject")[0]
else:
project = self.file.by_type("IfcContext")[0]
site = self.find_decomposed_ifc_class(project, "IfcSite")
if site and self.is_element_far_away(site[0]):
if site and self.is_element_far_away(site[0], is_meters=False):
return self.guess_georeferencing(site[0])
building = self.find_decomposed_ifc_class(project, "IfcBuilding")
if building and self.is_element_far_away(building[0]):
if building and self.is_element_far_away(building[0], is_meters=False):
return self.guess_georeferencing(building[0])
return self.guess_absolute_coordinate()
@@ -450,7 +482,6 @@ class IfcImporter:
grid_collection.objects.link(obj)
def create_type_products(self):
type_products = self.file.by_type("IfcTypeProduct")
for collection in self.project["blender"].children:
if collection.name == "Types":
self.type_collection = collection
@@ -458,7 +489,15 @@ class IfcImporter:
if not self.type_collection:
self.type_collection = bpy.data.collections.new("Types")
self.project["blender"].children.link(self.type_collection)
if self.filter_mode in ["WHITELIST", "BLACKLIST"]:
type_products = set([ifcopenshell.util.element.get_type(e) for e in self.elements])
else:
type_products = self.file.by_type("IfcTypeProduct")
for type_product in type_products:
if not type_product:
continue
self.create_type_product(type_product)
def create_type_product(self, element):
@@ -546,12 +585,20 @@ class IfcImporter:
if not valid_file:
return False
checkpoint = time.time()
total = 0
total_created = 0
approx_total_products = len(self.include_elements) or len(self.file.by_type("IfcElement"))
start_progress = self.progress
progress_range = 85 - start_progress
while True:
total += 1
if total % 250 == 0:
print("{} elements processed in {:.2f}s ...".format(total, time.time() - checkpoint))
if total_created % 250 == 0:
print(
"{} / ~{} elements processed in {:.2f}s ...".format(
total_created, approx_total_products, time.time() - checkpoint
)
)
checkpoint = time.time()
if approx_total_products:
self.update_progress(((total_created / approx_total_products) * progress_range) + start_progress)
shape = iterator.get()
if shape:
product = self.file.by_id(shape.guid)
@@ -565,18 +612,32 @@ class IfcImporter:
pass
else:
self.create_product(product, shape)
total_created += 1
if not iterator.next():
break
print("Done creating geometry")
def create_empty_products(self):
for element in self.file.by_type("IfcProduct"):
def create_empty_and_2d_elements(self):
curve_products = []
if self.filter_mode == "WHITELIST":
self.elements = self.include_elements
elif self.filter_mode == "BLACKLIST":
self.elements = [e for e in self.file.by_type("IfcElement") if e not in self.exclude_elements]
else:
self.elements = self.file.by_type("IfcElement")
for element in self.elements:
if element.id() in self.added_data:
continue
if element.is_a("IfcPort"):
continue
if not element.Representation:
self.create_product(element)
else:
curve_products.append(element)
if curve_products:
self.create_curve_products(curve_products)
def create_annotation(self):
self.create_curve_products(self.file.by_type("IfcAnnotation"))
@@ -911,7 +972,6 @@ class IfcImporter:
def set_ifc_file(self):
bpy.context.scene.BIMProperties.ifc_file = self.ifc_import_settings.input_file
IfcStore.file = self.file
IfcStore.path = self.ifc_import_settings.input_file
def calculate_unit_scale(self):
@@ -947,8 +1007,13 @@ class IfcImporter:
)
def create_project(self):
self.project = {"ifc": self.file.by_type("IfcProject")[0]}
self.project["blender"] = bpy.data.collections.new("IfcProject/{}".format(self.project["ifc"].Name))
if self.file.schema == "IFC2X3":
self.project = {"ifc": self.file.by_type("IfcProject")[0]}
else:
self.project = {"ifc": self.file.by_type("IfcContext")[0]}
self.project["blender"] = bpy.data.collections.new(
"{}/{}".format(self.project["ifc"].is_a(), self.project["ifc"].Name)
)
obj = self.create_product(self.project["ifc"])
if obj:
self.project["blender"].objects.link(obj)
@@ -1012,10 +1077,14 @@ class IfcImporter:
def create_materials(self):
for material in self.file.by_type("IfcMaterial"):
blender_material = bpy.data.materials.new(material.Name)
self.link_element(material, blender_material)
self.material_creator.materials[material.id()] = blender_material
blender_material.use_fake_user = True
self.create_material(material)
def create_material(self, material):
blender_material = bpy.data.materials.new(material.Name)
self.link_element(material, blender_material)
self.material_creator.materials[material.id()] = blender_material
blender_material.use_fake_user = True
return blender_material
def create_styles(self):
parsed_styles = set()
@@ -1031,11 +1100,13 @@ class IfcImporter:
for style in self.file.by_type("IfcSurfaceStyle"):
if style.id() in parsed_styles:
continue
self.create_style(style)
def create_style(self, style, blender_material=None):
if not blender_material:
name = style.Name or str(style.id())
blender_material = bpy.data.materials.new(name)
self.create_style(style, blender_material)
def create_style(self, style, blender_material):
old_definition_id = blender_material.BIMObjectProperties.ifc_definition_id
if not old_definition_id:
self.link_element(style, blender_material)
@@ -1077,7 +1148,7 @@ class IfcImporter:
self.place_object_in_spatial_tree(self.file.by_id(ifc_definition_id), obj)
def place_object_in_spatial_tree(self, element, obj):
if element.is_a("IfcProject"):
if element.is_a() in ["IfcProject", "IfcProjectLibrary"]:
return
elif element.is_a("IfcTypeObject"):
self.type_collection.objects.link(obj)
@@ -17,7 +17,7 @@ class AssignObject(bpy.types.Operator):
def _execute(self, context):
self.file = IfcStore.get_file()
related_objects = (
[bpy.data.objects.get(self.related_object)] if self.related_object else bpy.context.selected_objects
[bpy.data.objects.get(self.related_object)] if self.related_object else context.selected_objects
)
relating_object = bpy.data.objects.get(self.relating_object)
if not relating_object or not relating_object.BIMObjectProperties.ifc_definition_id:
@@ -40,7 +40,7 @@ class AssignObject(bpy.types.Operator):
spatial_collection = bpy.data.collections.get(related_object.name)
relating_collection = bpy.data.collections.get(relating_object.name)
if spatial_collection:
self.remove_collection(bpy.context.scene.collection, spatial_collection)
self.remove_collection(context.scene.collection, spatial_collection)
for collection in bpy.data.collections:
if collection == relating_collection:
if not collection.children.get(spatial_collection.name):
@@ -67,8 +67,8 @@ class EnableEditingAggregate(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
bpy.context.active_object.BIMObjectProperties.relating_object = None
bpy.context.active_object.BIMObjectProperties.is_editing_aggregate = True
context.active_object.BIMObjectProperties.relating_object = None
context.active_object.BIMObjectProperties.is_editing_aggregate = True
return {"FINISHED"}
@@ -79,7 +79,7 @@ class DisableEditingAggregate(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
obj.BIMObjectProperties.is_editing_aggregate = False
return {"FINISHED"}
@@ -94,9 +94,9 @@ class AddAggregate(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
aggregate_collection = bpy.data.collections.new("IfcElementAssembly/Assembly")
bpy.context.scene.collection.children.link(aggregate_collection)
context.scene.collection.children.link(aggregate_collection)
aggregate = bpy.data.objects.new("Assembly", None)
aggregate_collection.objects.link(aggregate)
bpy.ops.bim.assign_class(obj=aggregate.name, ifc_class="IfcElementAssembly")
@@ -104,12 +104,6 @@ class EditAttributes(bpy.types.Operator):
ifcopenshell.api.run(
"attribute.edit_attributes", self.file, **{"product": product, "attributes": attributes}
)
if "Name" in attributes:
new_name = "{}/{}".format(product.is_a(), product.Name or "Unnamed")
collection = bpy.data.collections.get(obj.name)
if collection:
collection.name = new_name
obj.name = new_name
Data.load(IfcStore.get_file(), oprops.ifc_definition_id)
bpy.ops.bim.disable_editing_attributes(obj=obj.name, obj_type=self.obj_type)
return {"FINISHED"}
@@ -121,11 +115,11 @@ class GenerateGlobalId(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
index = bpy.context.active_object.BIMAttributeProperties.attributes.find("GlobalId")
index = context.active_object.BIMAttributeProperties.attributes.find("GlobalId")
if index >= 0:
global_id = bpy.context.active_object.BIMAttributeProperties.attributes[index]
global_id = context.active_object.BIMAttributeProperties.attributes[index]
else:
global_id = bpy.context.active_object.BIMAttributeProperties.attributes.add()
global_id = context.active_object.BIMAttributeProperties.attributes.add()
global_id.name = "GlobalId"
global_id.data_type = "string"
global_id.string_value = ifcopenshell.guid.new()
@@ -16,7 +16,7 @@ class AuginLogin(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = bpy.context.scene.AuginProperties
props = context.scene.AuginProperties
url = "https://server.auge.pro.br/API/v3/augin_rest.php/user_login"
payload = {"email": props.username, "password": props.password}
@@ -36,7 +36,7 @@ class AuginReset(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = bpy.context.scene.AuginProperties
props = context.scene.AuginProperties
props.is_success = False
return {"FINISHED"}
@@ -49,7 +49,7 @@ class AuginCreateNewModel(bpy.types.Operator):
def execute(self, context):
import boto3
from botocore.config import Config
props = bpy.context.scene.AuginProperties
props = context.scene.AuginProperties
# Create project
url = "https://server.auge.pro.br/API/v3/augin_rest.php/new_model"
@@ -113,7 +113,7 @@ class AuginCreateNewModel(bpy.types.Operator):
context.scene.render.image_settings.file_format = old_file_format
context.scene.render.filepath = old_filepath
client.upload_file(bpy.context.scene.BIMProperties.ifc_file, result["s3_bucket"], result["model_path"])
client.upload_file(context.scene.BIMProperties.ifc_file, result["s3_bucket"], result["model_path"])
client.upload_file(thumb_path, result["s3_bucket"], result["thumb_path"])
@@ -121,8 +121,8 @@ class AuginCreateNewModel(bpy.types.Operator):
url = "https://server.auge.pro.br/API/v3/augin_rest.php/files_uploaded"
payload = {
"user_token": props.token,
"ifc_filesize": os.path.getsize(bpy.context.scene.BIMProperties.ifc_file),
"model_filesize": os.path.getsize(bpy.context.scene.BIMProperties.ifc_file),
"ifc_filesize": os.path.getsize(context.scene.BIMProperties.ifc_file),
"model_filesize": os.path.getsize(context.scene.BIMProperties.ifc_file),
"thumb_filesize": os.path.getsize(thumb_path),
"model_upload_path": result["model_path"],
"thumb_upload_path": result["thumb_path"],
@@ -28,7 +28,7 @@ class BIM_PT_augin(bpy.types.Panel):
row = layout.row()
row.label(text="Logged in as " + props.username)
if not bpy.context.scene.BIMProperties.ifc_file:
if not context.scene.BIMProperties.ifc_file:
row = layout.row()
row.label(text="No IFC Found")
return
@@ -3,6 +3,9 @@ import bpy
import bcf
import bcf.bcfxml
import bcf.v2.data
import numpy as np
import ifcopenshell
import ifcopenshell.util.unit
from . import bcfstore
from blenderbim.bim.ifc import IfcStore
from math import radians, degrees, atan, tan, cos, sin
@@ -14,11 +17,11 @@ class NewBcfProject(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
bpy.context.scene.BCFProperties.is_loaded = False
context.scene.BCFProperties.is_loaded = False
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.new_project()
bpy.ops.bim.load_bcf_project()
bpy.context.scene.BCFProperties.is_loaded = True
context.scene.BCFProperties.is_loaded = True
return {"FINISHED"}
@@ -30,14 +33,14 @@ class LoadBcfProject(bpy.types.Operator):
filter_glob: bpy.props.StringProperty(default="*.bcf;*.bcfzip", options={"HIDDEN"})
def execute(self, context):
bpy.context.scene.BCFProperties.is_loaded = False
context.scene.BCFProperties.is_loaded = False
if self.filepath:
bcfstore.BcfStore.bcfxml = bcf.bcfxml.load(self.filepath)
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.get_project()
bpy.context.scene.BCFProperties.name = bcfxml.project.name
context.scene.BCFProperties.name = bcfxml.project.name
bpy.ops.bim.load_bcf_topics()
bpy.context.scene.BCFProperties.is_loaded = True
context.scene.BCFProperties.is_loaded = True
return {"FINISHED"}
def invoke(self, context, event):
@@ -53,11 +56,11 @@ class LoadBcfTopics(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.get_topics()
while len(bpy.context.scene.BCFProperties.topics) > 0:
bpy.context.scene.BCFProperties.topics.remove(0)
while len(context.scene.BCFProperties.topics) > 0:
context.scene.BCFProperties.topics.remove(0)
index = 0
for topic_guid in bcfxml.topics.keys():
new = bpy.context.scene.BCFProperties.topics.add()
new = context.scene.BCFProperties.topics.add()
bpy.ops.bim.load_bcf_topic(topic_guid = topic_guid, topic_index = index)
index += 1
return {"FINISHED"}
@@ -73,7 +76,7 @@ class LoadBcfTopic(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
topic = bcfxml.get_topic(self.topic_guid)
new = bpy.context.scene.BCFProperties.topics[self.topic_index]
new = context.scene.BCFProperties.topics[self.topic_index]
data_map = {
"name": topic.guid,
"title": topic.title,
@@ -143,7 +146,7 @@ class LoadBcfComments(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.get_comments(self.topic_guid)
blender_topic = bpy.context.scene.BCFProperties.topics.get(self.topic_guid)
blender_topic = context.scene.BCFProperties.topics.get(self.topic_guid)
while len(blender_topic.comments) > 0:
blender_topic.comments.remove(0)
for comment in bcfxml.topics[self.topic_guid].comments.values():
@@ -170,7 +173,7 @@ class EditBcfProjectName(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.project.name = bpy.context.scene.BCFProperties.name
bcfxml.project.name = context.scene.BCFProperties.name
bcfxml.edit_project()
return {"FINISHED"}
@@ -182,7 +185,7 @@ class EditBcfAuthor(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.author = bpy.context.scene.BCFProperties.author
bcfxml.author = context.scene.BCFProperties.author
return {"FINISHED"}
@@ -192,7 +195,7 @@ class EditBcfTopicName(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
bcfxml = bcfstore.BcfStore.get_bcfxml()
topic = bcfxml.topics[blender_topic.name]
@@ -207,7 +210,7 @@ class EditBcfTopic(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
bcfxml = bcfstore.BcfStore.get_bcfxml()
@@ -250,7 +253,7 @@ class AddBcfTopic(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
bcfxml.add_topic()
new = bpy.context.scene.BCFProperties.topics.add()
new = context.scene.BCFProperties.topics.add()
new.name = "New Topic"
bpy.ops.bim.load_bcf_topics()
return {"FINISHED"}
@@ -263,7 +266,7 @@ class AddBcfBimSnippet(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
bim_snippet = bcf.v2.data.BimSnippet()
@@ -282,7 +285,7 @@ class AddBcfRelatedTopic(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
related_topic = None
for topic in bcfxml.topics.values():
@@ -306,7 +309,7 @@ class AddBcfHeaderFile(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
header_file = bcf.v2.data.HeaderFile()
@@ -329,9 +332,9 @@ class ViewBcfTopic(bpy.types.Operator):
topic_guid: bpy.props.StringProperty()
def execute(self, context):
for index, topic in enumerate(bpy.context.scene.BCFProperties.topics):
for index, topic in enumerate(context.scene.BCFProperties.topics):
if topic.guid.lower() == self.topic_guid.lower():
bpy.context.scene.BCFProperties.active_topic_index = index
context.scene.BCFProperties.active_topic_index = index
return {"FINISHED"}
@@ -341,44 +344,44 @@ class AddBcfViewpoint(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
if not bpy.context.scene.camera:
if not context.scene.camera:
return {"FINISHED"}
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
viewpoint = bcf.v2.data.Viewpoint()
if bpy.context.scene.camera.data.type == "ORTHO":
if context.scene.camera.data.type == "ORTHO":
camera = bcf.v2.data.OrthogonalCamera()
camera.view_to_world_scale = bpy.context.scene.camera.data.ortho_scale
camera.view_to_world_scale = context.scene.camera.data.ortho_scale
viewpoint.orthogonal_camera = camera
elif bpy.context.scene.camera.data.type == "PERSP":
elif context.scene.camera.data.type == "PERSP":
camera = bcf.v2.data.PerspectiveCamera()
camera.field_of_view = degrees(bpy.context.scene.camera.data.angle)
camera.field_of_view = degrees(context.scene.camera.data.angle)
viewpoint.perspective_camera = camera
camera.camera_view_point.x = bpy.context.scene.camera.location.x
camera.camera_view_point.y = bpy.context.scene.camera.location.y
camera.camera_view_point.z = bpy.context.scene.camera.location.z
direction = bpy.context.scene.camera.matrix_world.to_quaternion() @ Vector((0.0, 0.0, -1.0))
camera.camera_view_point.x = context.scene.camera.location.x
camera.camera_view_point.y = context.scene.camera.location.y
camera.camera_view_point.z = context.scene.camera.location.z
direction = context.scene.camera.matrix_world.to_quaternion() @ Vector((0.0, 0.0, -1.0))
camera.camera_direction.x = direction.x
camera.camera_direction.y = direction.y
camera.camera_direction.z = direction.z
up = bpy.context.scene.camera.matrix_world.to_quaternion() @ Vector((0.0, 1.0, 0.0))
up = context.scene.camera.matrix_world.to_quaternion() @ Vector((0.0, 1.0, 0.0))
camera.camera_up_vector.x = up.x
camera.camera_up_vector.y = up.y
camera.camera_up_vector.z = up.z
old_file_format = bpy.context.scene.render.image_settings.file_format
bpy.context.scene.render.image_settings.file_format = "PNG"
old_filepath = bpy.context.scene.render.filepath
bpy.context.scene.render.filepath = os.path.join(bpy.context.scene.BIMProperties.data_dir, "snapshot.png")
old_file_format = context.scene.render.image_settings.file_format
context.scene.render.image_settings.file_format = "PNG"
old_filepath = context.scene.render.filepath
context.scene.render.filepath = os.path.join(context.scene.BIMProperties.data_dir, "snapshot.png")
bpy.ops.render.opengl(write_still=True)
viewpoint.snapshot = bpy.context.scene.render.filepath
viewpoint.snapshot = context.scene.render.filepath
bcfxml.add_viewpoint(topic, viewpoint)
bpy.context.scene.render.filepath = old_filepath
bpy.context.scene.render.image_settings.file_format = old_file_format
context.scene.render.filepath = old_filepath
context.scene.render.image_settings.file_format = old_file_format
props.active_topic_index = props.active_topic_index # refreshes the BCF Topic
return {"FINISHED"}
@@ -390,7 +393,7 @@ class RemoveBcfViewpoint(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
viewpoint_guid = blender_topic.viewpoints
topic = bcfxml.topics[blender_topic.name]
@@ -407,7 +410,7 @@ class RemoveBcfFile(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
bcfxml.delete_file(topic, self.index)
@@ -422,7 +425,7 @@ class AddBcfReferenceLink(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
if not blender_topic.reference_link:
@@ -441,7 +444,7 @@ class AddBcfDocumentReference(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
if not blender_topic.document_reference:
@@ -463,7 +466,7 @@ class AddBcfLabel(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
if not blender_topic.label:
@@ -483,7 +486,7 @@ class EditBcfReferenceLinks(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
for index, reference_link in enumerate(topic.reference_links):
@@ -501,7 +504,7 @@ class EditBcfLabels(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
for index, label in enumerate(blender_topic.labels):
@@ -520,7 +523,7 @@ class RemoveBcfReferenceLink(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
del topic.reference_links[self.index]
@@ -537,7 +540,7 @@ class RemoveBcfLabel(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
del topic.labels[self.index]
@@ -553,7 +556,7 @@ class RemoveBcfBimSnippet(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
bcfxml.delete_bim_snippet(topic)
@@ -571,7 +574,7 @@ class RemoveBcfDocumentReference(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
bcfxml.delete_document_reference(topic, self.index)
@@ -587,7 +590,7 @@ class RemoveBcfRelatedTopic(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
del topic.related_topics[self.index]
@@ -604,7 +607,7 @@ class RemoveBcfComment(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
bcfxml.delete_comment(self.comment_guid, topic)
@@ -620,7 +623,7 @@ class EditBcfComment(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
blender_comment = blender_topic.comments.get(self.comment_guid)
topic = bcfxml.topics[blender_topic.name]
@@ -639,7 +642,7 @@ class AddBcfComment(bpy.types.Operator):
def execute(self, context):
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
if not blender_topic.comment:
@@ -662,7 +665,7 @@ class ActivateBcfViewpoint(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
bcfxml = bcfstore.BcfStore.get_bcfxml()
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
blender_topic = props.topics[props.active_topic_index]
topic = bcfxml.topics[blender_topic.name]
if not topic.viewpoints:
@@ -673,11 +676,11 @@ class ActivateBcfViewpoint(bpy.types.Operator):
obj = bpy.data.objects.get("Viewpoint")
if not obj:
obj = bpy.data.objects.new("Viewpoint", bpy.data.cameras.new("Viewpoint"))
bpy.context.scene.collection.objects.link(obj)
bpy.context.scene.camera = obj
context.scene.collection.objects.link(obj)
context.scene.camera = obj
cam_width = bpy.context.scene.render.resolution_x
cam_height = bpy.context.scene.render.resolution_y
cam_width = context.scene.render.resolution_x
cam_height = context.scene.render.resolution_y
cam_aspect = cam_width / cam_height
if viewpoint.snapshot:
@@ -697,9 +700,30 @@ class ActivateBcfViewpoint(bpy.types.Operator):
else:
background.frame_method = "CROP"
background.display_depth = "FRONT"
area = next(area for area in bpy.context.screen.areas if area.type == "VIEW_3D")
area = next(area for area in context.screen.areas if area.type == "VIEW_3D")
area.spaces[0].region_3d.view_perspective = "CAMERA"
if self.file:
self.set_viewpoint_components(viewpoint)
gp = bpy.data.grease_pencils.get("BCF")
if gp:
bpy.data.grease_pencils.remove(gp)
if viewpoint.lines:
self.draw_lines(viewpoint, context)
self.delete_clipping_planes(context)
if viewpoint.clipping_planes:
self.create_clipping_planes(viewpoint)
self.delete_bitmaps(context)
if viewpoint.bitmaps:
self.create_bitmaps(bcfxml, viewpoint, topic)
self.setup_camera(viewpoint, obj, cam_aspect)
return {"FINISHED"}
def setup_camera(self, viewpoint, obj, cam_aspect):
if viewpoint.orthogonal_camera:
camera = viewpoint.orthogonal_camera
obj.data.type = "ORTHO"
@@ -713,72 +737,115 @@ class ActivateBcfViewpoint(bpy.types.Operator):
# https://blender.stackexchange.com/questions/23431/how-to-set-camera-horizontal-and-vertical-fov
obj.data.angle = 2 * atan((0.5 * cam_height) / (0.5 * cam_width / tan(radians(camera.field_of_view) / 2)))
self.set_viewpoint_components(viewpoint)
gp = bpy.data.grease_pencils.get("BCF")
if gp:
bpy.data.grease_pencils.remove(gp)
if viewpoint.lines:
self.draw_lines(viewpoint)
self.delete_clipping_planes()
if viewpoint.clipping_planes:
self.create_clipping_planes(viewpoint)
self.delete_bitmaps()
if viewpoint.bitmaps:
self.create_bitmaps(bcfxml, viewpoint, topic)
z_axis = Vector((-camera.camera_direction.x, -camera.camera_direction.y, -camera.camera_direction.z)).normalized()
y_axis = Vector((camera.camera_up_vector.x, camera.camera_up_vector.y, camera.camera_up_vector.z)).normalized()
x_axis = y_axis.cross(z_axis).normalized()
rotation = Matrix((x_axis, y_axis, z_axis))
rotation.invert()
location = Vector((camera.camera_view_point.x, camera.camera_view_point.y, camera.camera_view_point.z))
obj.matrix_world = rotation.to_4x4()
obj.location = location
return {"FINISHED"}
matrix = np.matrix((
[x_axis[0], y_axis[0], z_axis[0], camera.camera_view_point.x],
[x_axis[1], y_axis[1], z_axis[1], camera.camera_view_point.y],
[x_axis[2], y_axis[2], z_axis[2], camera.camera_view_point.z],
[0, 0, 0, 1],
))
props = bpy.context.scene.BIMGeoreferenceProperties
if props.has_blender_offset:
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file)
matrix = ifcopenshell.util.geolocation.global2local(
matrix,
float(props.blender_eastings) * unit_scale,
float(props.blender_northings) * unit_scale,
float(props.blender_orthogonal_height) * unit_scale,
float(props.blender_x_axis_abscissa),
float(props.blender_x_axis_ordinate),
)
obj.matrix_world = Matrix(matrix.tolist())
def set_viewpoint_components(self, viewpoint):
if not viewpoint.components:
return
selected_global_ids = [s.ifc_guid for s in viewpoint.components.selection]
# Operators with context overrides are used because they are
# significantly faster than looping through all objects
exception_global_ids = [v.ifc_guid for v in viewpoint.components.visibility.exceptions]
if viewpoint.components.visibility.default_visibility:
old = bpy.context.area.type
bpy.context.area.type = "VIEW_3D"
bpy.ops.object.hide_view_clear()
bpy.context.area.type = old
for global_id in exception_global_ids:
obj = IfcStore.get_element(global_id)
if obj:
obj.hide_set(True)
else:
objs = []
for global_id in exception_global_ids:
obj = IfcStore.get_element(global_id)
if obj:
objs.append(obj)
if objs:
old = bpy.context.area.type
bpy.context.area.type = "VIEW_3D"
context_override = {}
context_override["object"] = context_override["active_object"] = objs[0]
context_override["selected_objects"] = context_override["selected_editable_objects"] = objs
bpy.ops.object.hide_view_set(context_override, unselected=True)
bpy.context.area.type = old
if viewpoint.components.view_setup_hints:
if not viewpoint.components.view_setup_hints.spaces_visible:
self.hide_spaces()
if viewpoint.components.view_setup_hints.openings_visible is not None:
self.set_openings_visibility(viewpoint.components.view_setup_hints.openings_visible)
else:
self.hide_spaces()
self.set_openings_visibility(False)
self.set_selection(viewpoint)
self.set_colours(viewpoint)
def hide_spaces(self):
old = bpy.context.area.type
bpy.context.area.type = "VIEW_3D"
bpy.ops.object.select_pattern(pattern="IfcSpace/*")
bpy.ops.object.hide_view_set({})
bpy.context.area.type = old
def set_openings_visibility(self, is_visible):
for collection in self.get_opening_collections():
collection.hide_viewport = not is_visible
def set_selection(self, viewpoint):
selected_global_ids = [s.ifc_guid for s in viewpoint.components.selection]
bpy.ops.object.select_all(action="DESELECT")
for global_id in selected_global_ids:
obj = IfcStore.get_element(global_id)
if obj:
obj.select_set(True)
def set_colours(self, viewpoint):
global_id_colours = {}
for coloring in viewpoint.components.coloring:
for component in coloring.components:
global_id_colours.setdefault(component.ifc_guid, coloring.color)
for global_id, color in global_id_colours.items():
obj = IfcStore.get_element(global_id)
if obj:
obj.color = self.hex_to_rgb(color)
for obj in bpy.data.objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
global_id = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id).GlobalId
is_visible = viewpoint.components.visibility.default_visibility
if global_id in exception_global_ids:
is_visible = not is_visible
if not is_visible:
obj.hide_set(True)
continue
if "IfcSpace" in obj.name:
if viewpoint.components.view_setup_hints:
is_visible = viewpoint.components.view_setup_hints.spaces_visible
else:
is_visible = False
elif "IfcOpeningElement" in obj.name:
if viewpoint.components.view_setup_hints:
is_visible = viewpoint.components.view_setup_hints.openings_visible
else:
is_visible = False
obj.hide_set(not is_visible)
if not is_visible:
continue
obj.select_set(global_id in selected_global_ids)
if global_id in global_id_colours:
obj.color = self.hex_to_rgb(global_id_colours[global_id])
def get_opening_collections(self):
collections = []
for collection in bpy.context.view_layer.layer_collection.children:
opening_collection = collection.children.get("IfcOpeningElements")
if opening_collection:
collections.append(opening_collection)
return collections
def draw_lines(self, viewpoint):
def draw_lines(self, viewpoint, context):
gp = bpy.data.grease_pencils.new("BCF")
scene = bpy.context.scene
scene = context.scene
scene.grease_pencil = gp
scene.frame_set(1)
layer = gp.layers.new("BCF Annotation", set_active=True)
@@ -808,19 +875,19 @@ class ActivateBcfViewpoint(bpy.types.Operator):
)
n += 1
def delete_clipping_planes(self):
def delete_clipping_planes(self, context):
collection = bpy.data.collections.get("Sections")
if not collection:
return
for section in collection.objects:
bpy.context.view_layer.objects.active = section
context.view_layer.objects.active = section
bpy.ops.bim.remove_section_plane()
def delete_bitmaps(self):
def delete_bitmaps(self, context):
collection = bpy.data.collections.get("Bitmaps")
if not collection:
collection = bpy.data.collections.new("Bitmaps")
bpy.context.scene.collection.children.link(collection)
context.scene.collection.children.link(collection)
for bitmap in collection.objects:
bpy.data.objects.remove(bitmap)
@@ -860,7 +927,7 @@ class OpenBcfReferenceLink(bpy.types.Operator):
index: bpy.props.IntProperty()
def execute(self, context):
webbrowser.open(bpy.context.scene.BCFProperties.topic_links[self.index].name)
webbrowser.open(context.scene.BCFProperties.topic_links[self.index].name)
return {"FINISHED"}
@@ -872,7 +939,7 @@ class SelectBcfHeaderFile(bpy.types.Operator):
def execute(self, context):
if self.filepath:
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
topic = props.topics[props.active_topic_index]
topic.file_reference = self.filepath
return {"FINISHED"}
@@ -890,7 +957,7 @@ class SelectBcfBimSnippetReference(bpy.types.Operator):
def execute(self, context):
if self.filepath:
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
topic = props.topics[props.active_topic_index]
topic.bim_snippet_reference = self.filepath
return {"FINISHED"}
@@ -908,7 +975,7 @@ class SelectBcfDocumentReference(bpy.types.Operator):
def execute(self, context):
if self.filepath:
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
topic = props.topics[props.active_topic_index]
topic.document_reference = self.filepath
return {"FINISHED"}
@@ -23,37 +23,37 @@ def purge():
def updateBcfReferenceLink(self, context):
if bpy.context.scene.BCFProperties.is_loaded:
if context.scene.BCFProperties.is_loaded:
bpy.ops.bim.edit_bcf_reference_links()
def updateBcfLabel(self, context):
if bpy.context.scene.BCFProperties.is_loaded:
if context.scene.BCFProperties.is_loaded:
bpy.ops.bim.edit_bcf_labels()
def updateBcfProjectName(self, context):
if bpy.context.scene.BCFProperties.is_loaded:
if context.scene.BCFProperties.is_loaded:
bpy.ops.bim.edit_bcf_project_name()
def updateBcfAuthor(self, context):
if bpy.context.scene.BCFProperties.is_loaded:
if context.scene.BCFProperties.is_loaded:
bpy.ops.bim.edit_bcf_author()
def updateBcfTopicName(self, context):
if bpy.context.scene.BCFProperties.is_loaded:
if context.scene.BCFProperties.is_loaded:
bpy.ops.bim.edit_bcf_topic_name()
def updateBcfTopicIsEditable(self, context):
if bpy.context.scene.BCFProperties.is_loaded and not self.is_editable:
if context.scene.BCFProperties.is_loaded and not self.is_editable:
bpy.ops.bim.edit_bcf_topic()
def updateBcfCommentIsEditable(self, context):
if bpy.context.scene.BCFProperties.is_loaded and not self.is_editable:
if context.scene.BCFProperties.is_loaded and not self.is_editable:
bpy.ops.bim.edit_bcf_comment(comment_guid = self.name)
@@ -61,7 +61,7 @@ def refreshBcfTopic(self, context):
global bcfviewpoints_enum
bcfviewpoints_enum = None
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
bcfxml = bcfstore.BcfStore.get_bcfxml()
topic = props.topics[props.active_topic_index]
header = bcfxml.get_header(topic.name)
@@ -80,7 +80,7 @@ def getBcfViewpoints(self, context):
global bcfviewpoints_enum
if bcfviewpoints_enum is None:
bcfviewpoints_enum = []
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
bcfxml = bcfstore.BcfStore.get_bcfxml()
topic = props.topics[props.active_topic_index]
viewpoints = bcfxml.get_viewpoints(topic.name)
@@ -17,7 +17,7 @@ class BIM_PT_bcf(Panel):
layout.use_property_decorate = False
scene = context.scene
props = bpy.context.scene.BCFProperties
props = scene.BCFProperties
row = layout.row(align=True)
row.operator("bim.new_bcf_project", text="New Project")
@@ -34,7 +34,7 @@ class BIM_PT_bcf(Panel):
row = layout.row()
row.prop(props, "author")
props = bpy.context.scene.BCFProperties
props = context.scene.BCFProperties
row = layout.row()
row.template_list("BIM_UL_topics", "", props, "topics", props, "active_topic_index")
col = row.column(align=True)
@@ -93,7 +93,7 @@ class BIM_PT_bcf_metadata(Panel):
layout.use_property_decorate = False
scene = context.scene
props = bpy.context.scene.BCFProperties
props = scene.BCFProperties
if props.active_topic_index >= len(props.topics):
layout.label(text="No BCF project is loaded")
@@ -236,7 +236,7 @@ class BIM_PT_bcf_comments(Panel):
layout.use_property_decorate = False
scene = context.scene
props = bpy.context.scene.BCFProperties
props = scene.BCFProperties
if props.active_topic_index >= len(props.topics):
layout.label(text="No BCF project is loaded")
@@ -52,11 +52,11 @@ class BIMTesterPurge(bpy.types.Operator):
def execute(self, context):
filename = os.path.join(
bpy.context.scene.BimTesterProperties.features_dir,
bpy.context.scene.BimTesterProperties.features_file + ".feature",
context.scene.BimTesterProperties.features_dir,
context.scene.BimTesterProperties.features_file + ".feature",
)
cwd = os.getcwd()
os.chdir(bpy.context.scene.BimTesterProperties.features_dir)
os.chdir(context.scene.BimTesterProperties.features_dir)
bimtester.clean.TestPurger().purge()
os.chdir(cwd)
return {"FINISHED"}
@@ -71,7 +71,7 @@ class SelectFeature(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.BimTesterProperties.feature = self.filepath
context.scene.BimTesterProperties.feature = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -88,7 +88,7 @@ class SelectSteps(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.BimTesterProperties.steps = self.filepath
context.scene.BimTesterProperties.steps = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -120,14 +120,14 @@ class RejectElement(bpy.types.Operator):
def execute(self, context):
lines = []
self.file = IfcStore.get_file()
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
lines.append(
" * The element {} should not exist because {}".format(
self.file.by_id(obj.BIMObjectProperties.ifc_definition_id).GlobalId,
bpy.context.scene.BimTesterProperties.qa_reject_element_reason,
context.scene.BimTesterProperties.qa_reject_element_reason,
)
)
QAHelper.append_to_scenario(lines)
QAHelper.append_to_scenario(lines, context)
return {"FINISHED"}
@@ -138,12 +138,12 @@ class ApproveClass(bpy.types.Operator):
def execute(self, context):
lines = []
self.file = IfcStore.get_file()
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
lines.append(" * The element {} is an {}".format(element.GlobalId, element.is_a()))
QAHelper.append_to_scenario(lines)
QAHelper.append_to_scenario(lines, context)
return {"FINISHED"}
@@ -154,16 +154,16 @@ class RejectClass(bpy.types.Operator):
def execute(self, context):
lines = []
self.file = IfcStore.get_file()
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
lines.append(
" * The element {} is an {}".format(
self.file.by_id(obj.BIMObjectProperties.ifc_definition_id).GlobalId,
bpy.context.scene.BimTesterProperties.audit_ifc_class,
context.scene.BimTesterProperties.audit_ifc_class,
)
)
QAHelper.append_to_scenario(lines)
QAHelper.append_to_scenario(lines, context)
return {"FINISHED"}
@@ -175,7 +175,7 @@ class SelectAudited(bpy.types.Operator):
def execute(self, context):
audited_global_ids = []
self.file = IfcStore.get_file()
for filename in Path(bpy.context.scene.BimTesterProperties.features_dir).glob("*.feature"):
for filename in Path(context.scene.BimTesterProperties.features_dir).glob("*.feature"):
with open(filename, "r") as feature_file:
lines = feature_file.readlines()
for line in lines:
@@ -183,7 +183,7 @@ class SelectAudited(bpy.types.Operator):
for word in words:
if self.is_a_global_id(word):
audited_global_ids.append(word)
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
if self.file.by_id(obj.BIMObjectProperties.ifc_definition_id).GlobalId in audited_global_ids:
@@ -196,10 +196,10 @@ class SelectAudited(bpy.types.Operator):
class QAHelper:
@classmethod
def append_to_scenario(cls, lines):
def append_to_scenario(cls, lines, context):
filename = os.path.join(
bpy.context.scene.BimTesterProperties.features_dir,
bpy.context.scene.BimTesterProperties.features_file + ".feature",
context.scene.BimTesterProperties.features_dir,
context.scene.BimTesterProperties.features_file + ".feature",
)
if os.path.exists(filename + "~"):
os.remove(filename + "~")
@@ -210,7 +210,7 @@ class QAHelper:
for source_line in source:
if (
"Scenario: " in source_line
and bpy.context.scene.BimTesterProperties.scenario == source_line.strip()[len("Scenario: ") :]
and context.scene.BimTesterProperties.scenario == source_line.strip()[len("Scenario: ") :]
):
is_in_scenario = True
elif is_in_scenario:
@@ -23,7 +23,7 @@ class ExportClashSets(bpy.types.Operator):
def execute(self, context):
self.filepath = bpy.path.ensure_ext(self.filepath, ".json")
clash_sets = []
for clash_set in bpy.context.scene.BIMClashProperties.clash_sets:
for clash_set in context.scene.BIMClashProperties.clash_sets:
self.a = []
self.b = []
for ab in ["a", "b"]:
@@ -56,7 +56,7 @@ class ImportClashSets(bpy.types.Operator):
with open(self.filepath) as f:
clash_sets = json.load(f)
for clash_set in clash_sets:
new = bpy.context.scene.BIMClashProperties.clash_sets.add()
new = context.scene.BIMClashProperties.clash_sets.add()
new.name = clash_set["name"]
new.tolerance = clash_set["tolerance"]
for clash_source in clash_set["a"]:
@@ -81,7 +81,7 @@ class AddClashSet(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
new = bpy.context.scene.BIMClashProperties.clash_sets.add()
new = context.scene.BIMClashProperties.clash_sets.add()
new.name = "New Clash Set"
new.tolerance = 0.01
return {"FINISHED"}
@@ -94,7 +94,7 @@ class RemoveClashSet(bpy.types.Operator):
index: bpy.props.IntProperty()
def execute(self, context):
bpy.context.scene.BIMClashProperties.clash_sets.remove(self.index)
context.scene.BIMClashProperties.clash_sets.remove(self.index)
return {"FINISHED"}
@@ -105,7 +105,7 @@ class AddClashSource(bpy.types.Operator):
group: bpy.props.StringProperty()
def execute(self, context):
clash_set = bpy.context.scene.BIMClashProperties.clash_sets[bpy.context.scene.BIMClashProperties.active_clash_set_index]
clash_set = context.scene.BIMClashProperties.clash_sets[context.scene.BIMClashProperties.active_clash_set_index]
source = getattr(clash_set, self.group).add()
return {"FINISHED"}
@@ -118,7 +118,7 @@ class RemoveClashSource(bpy.types.Operator):
group: bpy.props.StringProperty()
def execute(self, context):
clash_set = bpy.context.scene.BIMClashProperties.clash_sets[bpy.context.scene.BIMClashProperties.active_clash_set_index]
clash_set = context.scene.BIMClashProperties.clash_sets[context.scene.BIMClashProperties.active_clash_set_index]
getattr(clash_set, self.group).remove(self.index)
return {"FINISHED"}
@@ -133,7 +133,7 @@ class SelectClashSource(bpy.types.Operator):
group: bpy.props.StringProperty()
def execute(self, context):
clash_set = bpy.context.scene.BIMClashProperties.clash_sets[bpy.context.scene.BIMClashProperties.active_clash_set_index]
clash_set = context.scene.BIMClashProperties.clash_sets[context.scene.BIMClashProperties.active_clash_set_index]
getattr(clash_set, self.group)[self.index].name = self.filepath
return {"FINISHED"}
@@ -149,7 +149,7 @@ class SelectClashResults(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.BIMClashProperties.clash_results_path = self.filepath
context.scene.BIMClashProperties.clash_results_path = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -164,7 +164,7 @@ class SelectSmartGroupedClashesPath(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.BIMClashProperties.smart_grouped_clashes_path = self.filepath
context.scene.BIMClashProperties.smart_grouped_clashes_path = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -186,42 +186,42 @@ class ExecuteIfcClash(bpy.types.Operator):
return {"RUNNING_MODAL"}
def execute(self, context):
import ifcclash
from ifcclash import ifcclash
settings = ifcclash.IfcClashSettings()
settings = ifcclash.ClashSettings()
if ".json" not in self.filepath:
self.filepath = bpy.path.ensure_ext(self.filepath, ".bcf")
settings.output = self.filepath
settings.logger = logging.getLogger("Clash")
settings.logger.setLevel(logging.DEBUG)
ifc_clasher = ifcclash.IfcClasher(settings)
clasher = ifcclash.Clasher(settings)
if bpy.context.scene.BIMClashProperties.should_create_clash_snapshots:
if context.scene.BIMClashProperties.should_create_clash_snapshots:
def get_viewpoint_snapshot(self, viewpoint, mat):
def get_viewpoint_snapshot(viewpoint, mat):
camera = bpy.data.objects.get("IFC Clash Camera")
if not camera:
camera = bpy.data.objects.new("IFC Clash Camera", bpy.data.cameras.new("IFC Clash Camera"))
bpy.context.scene.collection.objects.link(camera)
context.scene.collection.objects.link(camera)
camera.matrix_world = Matrix(mat)
bpy.context.scene.camera = camera
context.scene.camera = camera
camera.data.angle = radians(60)
area = next(area for area in bpy.context.screen.areas if area.type == "VIEW_3D")
area = next(area for area in context.screen.areas if area.type == "VIEW_3D")
area.spaces[0].region_3d.view_perspective = "CAMERA"
area.spaces[0].shading.show_xray = True
bpy.context.scene.render.resolution_x = 480
bpy.context.scene.render.resolution_y = 270
bpy.context.scene.render.image_settings.file_format = "PNG"
bpy.context.scene.render.filepath = os.path.join(
bpy.context.scene.BIMProperties.data_dir, "snapshot.png"
context.scene.render.resolution_x = 480
context.scene.render.resolution_y = 270
context.scene.render.image_settings.file_format = "PNG"
context.scene.render.filepath = os.path.join(
context.scene.BIMProperties.data_dir, "snapshot.png"
)
bpy.ops.render.opengl(write_still=True)
return bpy.context.scene.render.filepath
return context.scene.render.filepath
ifcclash.IfcClasher.get_viewpoint_snapshot = get_viewpoint_snapshot
clasher.get_viewpoint_snapshot = get_viewpoint_snapshot
ifc_clasher.clash_sets = []
for clash_set in bpy.context.scene.BIMClashProperties.clash_sets:
clasher.clash_sets = []
for clash_set in context.scene.BIMClashProperties.clash_sets:
self.a = []
self.b = []
for ab in ["a", "b"]:
@@ -231,11 +231,12 @@ class ExecuteIfcClash(bpy.types.Operator):
clash_source["selector"] = data.selector
clash_source["mode"] = data.mode
getattr(self, ab).append(clash_source)
ifc_clasher.clash_sets.append(
{"name": clash_set.name, "tolerance": clash_set.tolerance, "a": self.a, "b": self.b}
)
ifc_clasher.clash()
ifc_clasher.export()
clash_set_data = {"name": clash_set.name, "tolerance": clash_set.tolerance, "a": self.a}
if self.b:
clash_set_data["b"] = self.b
clasher.clash_sets.append(clash_set_data)
clasher.clash()
clasher.export()
return {"FINISHED"}
@@ -256,8 +257,8 @@ class SelectIfcClashResults(bpy.types.Operator):
self.filepath = bpy.path.ensure_ext(self.filepath, ".json")
with open(self.filepath) as f:
clash_sets = json.load(f)
clash_set_name = bpy.context.scene.BIMClashProperties.clash_sets[
bpy.context.scene.BIMClashProperties.active_clash_set_index
clash_set_name = context.scene.BIMClashProperties.clash_sets[
context.scene.BIMClashProperties.active_clash_set_index
].name
global_ids = []
for clash_set in clash_sets:
@@ -268,7 +269,7 @@ class SelectIfcClashResults(bpy.types.Operator):
return {"CANCELLED"}
for clash in clash_set["clashes"].values():
global_ids.extend([clash["a_global_id"], clash["b_global_id"]])
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
@@ -287,7 +288,7 @@ class SmartClashGroup(bpy.types.Operator):
import ifcclash
settings = ifcclash.IfcClashSettings()
self.filepath = bpy.path.ensure_ext(bpy.context.scene.BIMClashProperties.clash_results_path, ".json")
self.filepath = bpy.path.ensure_ext(context.scene.BIMClashProperties.clash_results_path, ".json")
settings.output = self.filepath
settings.logger = logging.getLogger("Clash")
settings.logger.setLevel(logging.DEBUG)
@@ -297,21 +298,21 @@ class SmartClashGroup(bpy.types.Operator):
clash_sets = json.load(f)
# execute the smart grouping
save_path = bpy.path.ensure_ext(bpy.context.scene.BIMClashProperties.smart_grouped_clashes_path, ".json")
save_path = bpy.path.ensure_ext(context.scene.BIMClashProperties.smart_grouped_clashes_path, ".json")
smart_grouped_clashes = ifc_clasher.smart_group_clashes(
clash_sets, bpy.context.scene.BIMClashProperties.smart_clash_grouping_max_distance
clash_sets, context.scene.BIMClashProperties.smart_clash_grouping_max_distance
)
# save smart_groups to json
with open(save_path, "w") as f:
f.write(json.dumps(smart_grouped_clashes))
clash_set_name = bpy.context.scene.BIMClashProperties.clash_sets[
bpy.context.scene.BIMClashProperties.active_clash_set_index
clash_set_name = context.scene.BIMClashProperties.clash_sets[
context.scene.BIMClashProperties.active_clash_set_index
].name
# Reset the list of smart_clash_groups for the UI
bpy.context.scene.BIMClashProperties.smart_clash_groups.clear()
context.scene.BIMClashProperties.smart_clash_groups.clear()
for clash_set, smart_groups in smart_grouped_clashes.items():
# Only select the clashes that correspond to the actively selected IFC Clash Set
@@ -319,7 +320,7 @@ class SmartClashGroup(bpy.types.Operator):
continue
else:
for smart_group, global_id_pairs in smart_groups[0].items():
new_group = bpy.context.scene.BIMClashProperties.smart_clash_groups.add()
new_group = context.scene.BIMClashProperties.smart_clash_groups.add()
new_group.number = f"{smart_group}"
for pair in global_id_pairs:
@@ -336,17 +337,17 @@ class LoadSmartGroupsForActiveClashSet(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
smart_groups_path = bpy.path.ensure_ext(bpy.context.scene.BIMClashProperties.smart_grouped_clashes_path, ".json")
smart_groups_path = bpy.path.ensure_ext(context.scene.BIMClashProperties.smart_grouped_clashes_path, ".json")
clash_set_name = bpy.context.scene.BIMClashProperties.clash_sets[
bpy.context.scene.BIMClashProperties.active_clash_set_index
clash_set_name = context.scene.BIMClashProperties.clash_sets[
context.scene.BIMClashProperties.active_clash_set_index
].name
with open(smart_groups_path) as f:
smart_grouped_clashes = json.load(f)
# Reset the list of smart_clash_groups for the UI
bpy.context.scene.BIMClashProperties.smart_clash_groups.clear()
context.scene.BIMClashProperties.smart_clash_groups.clear()
for clash_set, smart_groups in smart_grouped_clashes.items():
# Only select the clashes that correspond to the actively selected IFC Clash Set
@@ -354,7 +355,7 @@ class LoadSmartGroupsForActiveClashSet(bpy.types.Operator):
continue
else:
for smart_group, global_id_pairs in smart_groups[0].items():
new_group = bpy.context.scene.BIMClashProperties.smart_clash_groups.add()
new_group = context.scene.BIMClashProperties.smart_clash_groups.add()
new_group.number = f"{smart_group}"
for pair in global_id_pairs:
for id in pair:
@@ -371,12 +372,12 @@ class SelectSmartGroup(bpy.types.Operator):
def execute(self, context):
# Select smart group in view
selected_smart_group = bpy.context.scene.BIMClashProperties.smart_clash_groups[
bpy.context.scene.BIMCLashProperties.active_smart_group_index
selected_smart_group = context.scene.BIMClashProperties.smart_clash_groups[
context.scene.BIMCLashProperties.active_smart_group_index
]
# print(selected_smart_group.number)
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
@@ -391,13 +392,13 @@ class SelectSmartGroup(bpy.types.Operator):
class BlenderClasher:
def process_clash_set(self):
def process_clash_set(self, context):
import collision
a_cm = collision.CollisionManager()
b_cm = collision.CollisionManager()
self.add_to_cm(a_cm, bpy.context.scene.BIMClashProperties.blender_clash_set_a)
self.add_to_cm(b_cm, bpy.context.scene.BIMClashProperties.blender_clash_set_b)
self.add_to_cm(a_cm, context.scene.BIMClashProperties.blender_clash_set_a, context)
self.add_to_cm(b_cm, context.scene.BIMClashProperties.blender_clash_set_b, context)
results = a_cm.in_collision_other(b_cm, return_data=True)
if not results[0]:
print("No clashes")
@@ -410,20 +411,20 @@ class BlenderClasher:
print(contact.raw.normal)
print(contact.raw.pos)
def add_to_cm(self, cm, object_names):
def add_to_cm(self, cm, object_names, context):
import ifcclash
for object_name in object_names:
name = object_name.name
obj = bpy.data.objects[name]
triangulated_mesh = self.triangulate_mesh(obj)
triangulated_mesh = self.triangulate_mesh(obj, context)
mesh = ifcclash.Mesh()
mesh.vertices = np.array([tuple(obj.matrix_world @ v.co) for v in triangulated_mesh.vertices])
mesh.faces = np.array([tuple(p.vertices) for p in triangulated_mesh.polygons])
cm.add_object(name, mesh)
def triangulate_mesh(self, obj):
mesh = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()
def triangulate_mesh(self, obj, context):
mesh = obj.evaluated_get(context.evaluated_depsgraph_get()).to_mesh()
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.triangulate(bm, faces=bm.faces)
@@ -439,10 +440,10 @@ class SetBlenderClashSetA(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
while len(bpy.context.scene.BIMClashProperties.blender_clash_set_a) > 0:
bpy.context.scene.BIMClashProperties.blender_clash_set_a.remove(0)
for obj in bpy.context.selected_objects:
new = bpy.context.scene.BIMClashProperties.blender_clash_set_a.add()
while len(context.scene.BIMClashProperties.blender_clash_set_a) > 0:
context.scene.BIMClashProperties.blender_clash_set_a.remove(0)
for obj in context.selected_objects:
new = context.scene.BIMClashProperties.blender_clash_set_a.add()
new.name = obj.name
return {"FINISHED"}
@@ -453,10 +454,10 @@ class SetBlenderClashSetB(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
while len(bpy.context.scene.BIMClashProperties.blender_clash_set_b) > 0:
bpy.context.scene.BIMClashProperties.blender_clash_set_b.remove(0)
for obj in bpy.context.selected_objects:
new = bpy.context.scene.BIMClashProperties.blender_clash_set_b.add()
while len(context.scene.BIMClashProperties.blender_clash_set_b) > 0:
context.scene.BIMClashProperties.blender_clash_set_b.remove(0)
for obj in context.selected_objects:
new = context.scene.BIMClashProperties.blender_clash_set_b.add()
new.name = obj.name
return {"FINISHED"}
@@ -467,5 +468,5 @@ class ExecuteBlenderClash(bpy.types.Operator):
def execute(self, context):
blender_clasher = BlenderClasher()
blender_clasher.process_clash_set()
blender_clasher.process_clash_set(context)
return {"FINISHED"}
@@ -41,7 +41,7 @@ class BIMClashProperties(PropertyGroup):
blender_clash_set_a: CollectionProperty(name="Blender Clash Set A", type=StrProperty)
blender_clash_set_b: CollectionProperty(name="Blender Clash Set B", type=StrProperty)
clash_sets: CollectionProperty(name="Clash Sets", type=ClashSet)
should_create_clash_snapshots: BoolProperty(name="Create Snapshots", default=True)
should_create_clash_snapshots: BoolProperty(name="Create Snapshots", default=False)
clash_results_path: StringProperty(name="Clash Results Path")
smart_grouped_clashes_path: StringProperty(name="Smart Grouped Clashes Path")
active_clash_set_index: IntProperty(name="Active Clash Set Index")
@@ -133,7 +133,7 @@ class EnableEditingClassificationReference(bpy.types.Operator):
obj: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
props = obj.BIMClassificationReferenceProperties
while len(props.reference_attributes) > 0:
props.reference_attributes.remove(0)
@@ -157,7 +157,7 @@ class DisableEditingClassificationReference(bpy.types.Operator):
obj: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
obj.BIMClassificationReferenceProperties.active_reference_id = 0
return {"FINISHED"}
@@ -173,7 +173,7 @@ class RemoveClassificationReference(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"classification.remove_reference",
@@ -198,7 +198,7 @@ class EditClassificationReference(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
props = obj.BIMClassificationReferenceProperties
attributes = {}
for attribute in props.reference_attributes:
@@ -228,7 +228,7 @@ class AddClassificationReference(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
classification = None
@@ -41,7 +41,7 @@ class BIM_PT_classifications(Panel):
row = self.layout.row(align=True)
row.prop(self.props.classification_attributes.get("Name"), "string_value", text="", icon="ASSET_MANAGER")
row.operator("bim.edit_classification", text="", icon="CHECKMARK")
row.operator("bim.disable_editing_classification", text="", icon="X")
row.operator("bim.disable_editing_classification", text="", icon="CANCEL")
for attribute in self.props.classification_attributes:
if attribute.name == "Name":
@@ -15,7 +15,7 @@ class SelectCobieIfcFile(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.COBieProperties.cobie_ifc_file = self.filepath
context.scene.COBieProperties.cobie_ifc_file = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -30,7 +30,7 @@ class SelectCobieJsonFile(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.COBieProperties.cobie_json_file = self.filepath
context.scene.COBieProperties.cobie_json_file = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -45,7 +45,7 @@ class ExecuteIfcCobie(bpy.types.Operator):
def execute(self, context):
from cobie import IfcCobieParser
props = bpy.context.scene.COBieProperties
props = context.scene.COBieProperties
output_dir = os.path.dirname(props.cobie_ifc_file)
@@ -21,9 +21,9 @@ class AddSubcontext(bpy.types.Operator):
"context.add_context",
self.file,
**{
"context": self.context or bpy.context.scene.BIMProperties.available_contexts,
"subcontext": self.subcontext or bpy.context.scene.BIMProperties.available_subcontexts,
"target_view": self.target_view or bpy.context.scene.BIMProperties.available_target_views,
"context": self.context or context.scene.BIMProperties.available_contexts,
"subcontext": self.subcontext or context.scene.BIMProperties.available_subcontexts,
"target_view": self.target_view or context.scene.BIMProperties.available_target_views,
},
)
Data.load(IfcStore.get_file())
@@ -19,6 +19,8 @@ classes = (
operator.DisableEditingCostSchedule,
operator.DisableEditingCostItemQuantity,
operator.DisableEditingCostItemValue,
operator.AddCostColumn,
operator.RemoveCostColumn,
operator.AddCostItem,
operator.AddSummaryCostItem,
operator.ExpandCostItem,
@@ -33,16 +35,24 @@ classes = (
operator.CopyCostItemValues,
operator.SelectCostItemProducts,
operator.SelectCostScheduleProducts,
operator.ImportCostScheduleCsv,
prop.CostItem,
prop.BIMCostProperties,
ui.BIM_PT_cost_schedules,
ui.BIM_UL_cost_items,
ui.BIM_UL_cost_columns,
)
def menu_func_import(self, context):
self.layout.operator(operator.ImportCostScheduleCsv.bl_idname, text="Cost Schedule (.csv)")
def register():
bpy.types.Scene.BIMCostProperties = bpy.props.PointerProperty(type=prop.BIMCostProperties)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
def unregister():
del bpy.types.Scene.BIMCostProperties
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
@@ -1,10 +1,12 @@
import os
import bpy
import json
import time
import ifcopenshell.api
import blenderbim.bim.helper
from blenderbim.bim.module.cost.prop import purge
from blenderbim.bim.ifc import IfcStore
from bpy_extras.io_utils import ImportHelper
from ifcopenshell.api.cost.data import Data
@@ -307,7 +309,7 @@ class AssignCostItemProduct(bpy.types.Operator):
def _execute(self, context):
related_objects = (
[bpy.data.objects.get(self.related_object)] if self.related_object else bpy.context.selected_objects
[bpy.data.objects.get(self.related_object)] if self.related_object else context.selected_objects
)
self.file = IfcStore.get_file()
ifcopenshell.api.run(
@@ -336,7 +338,7 @@ class UnassignCostItemProduct(bpy.types.Operator):
def _execute(self, context):
related_objects = (
[bpy.data.objects.get(self.related_object)] if self.related_object else bpy.context.selected_objects
[bpy.data.objects.get(self.related_object)] if self.related_object else context.selected_objects
)
self.file = IfcStore.get_file()
ifcopenshell.api.run(
@@ -420,7 +422,7 @@ class AddCostItemQuantity(bpy.types.Operator):
class RemoveCostItemQuantity(bpy.types.Operator):
bl_idname = "bim.remove_cost_item_quantity"
bl_label = "Add Cost Item Quantity"
bl_label = "Remove Cost Item Quantity"
bl_options = {"REGISTER", "UNDO"}
cost_item: bpy.props.IntProperty()
physical_quantity: bpy.props.IntProperty()
@@ -621,7 +623,7 @@ class SelectCostItemProducts(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
related_products = Data.cost_items[self.cost_item]["Controls"]
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
obj.select_set(False)
if obj.BIMObjectProperties.ifc_definition_id in related_products:
obj.select_set(True)
@@ -640,7 +642,7 @@ class SelectCostScheduleProducts(bpy.types.Operator):
for cost_item_id in Data.cost_schedules[self.cost_schedule]["Controls"]:
self.get_related_products(Data.cost_items[cost_item_id])
self.related_products = set(self.related_products)
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
obj.select_set(False)
if obj.BIMObjectProperties.ifc_definition_id in self.related_products:
obj.select_set(True)
@@ -650,3 +652,53 @@ class SelectCostScheduleProducts(bpy.types.Operator):
self.related_products.extend(cost_item["Controls"])
for child_id in cost_item["IsNestedBy"]:
self.get_related_products(Data.cost_items[child_id])
class ImportCostScheduleCsv(bpy.types.Operator, ImportHelper):
bl_idname = "import_cost_schedule_csv.bim"
bl_label = "Import Cost Schedule CSV"
bl_options = {"REGISTER", "UNDO"}
filename_ext = ".csv"
filter_glob: bpy.props.StringProperty(default="*.csv", options={"HIDDEN"})
def execute(self, context):
from ifc5d.csv2ifc import Csv2Ifc
self.file = IfcStore.get_file()
start = time.time()
csv2ifc = Csv2Ifc()
csv2ifc.csv = self.filepath
csv2ifc.file = self.file
csv2ifc.execute()
Data.load(IfcStore.get_file())
print("Import finished in {:.2f} seconds".format(time.time() - start))
return {"FINISHED"}
class AddCostColumn(bpy.types.Operator):
bl_idname = "bim.add_cost_column"
bl_label = "Add Cost Column"
bl_options = {"REGISTER", "UNDO"}
name: bpy.props.StringProperty()
def execute(self, context):
self.props = context.scene.BIMCostProperties
new = self.props.columns.add()
new.name = self.name
Data.set_categories([c.name for c in self.props.columns])
Data.load(IfcStore.get_file())
return {"FINISHED"}
class RemoveCostColumn(bpy.types.Operator):
bl_idname = "bim.remove_cost_column"
bl_label = "Remove Cost Column"
bl_options = {"REGISTER", "UNDO"}
name: bpy.props.StringProperty()
def execute(self, context):
self.props = context.scene.BIMCostProperties
self.props.columns.remove(self.props.columns.find(self.name))
Data.set_categories([c.name for c in self.props.columns])
Data.load(IfcStore.get_file())
return {"FINISHED"}
@@ -84,7 +84,7 @@ class BIMCostProperties(PropertyGroup):
cost_schedule_attributes: CollectionProperty(name="Cost Schedule Attributes", type=Attribute)
is_editing: StringProperty(name="Is Editing")
active_cost_schedule_id: IntProperty(name="Active Cost Schedule Id")
cost_items: CollectionProperty(name="Work Calendar", type=CostItem)
cost_items: CollectionProperty(name="Cost Items", type=CostItem)
active_cost_item_id: IntProperty(name="Active Cost Id")
cost_item_editing_type: StringProperty(name="Cost Item Editing Type")
active_cost_item_index: IntProperty(name="Active Cost Item Index")
@@ -105,3 +105,7 @@ class BIMCostProperties(PropertyGroup):
cost_category: StringProperty(name="Cost Category")
active_cost_item_value_id: IntProperty(name="Active Cost Item Value Id")
cost_value_attributes: CollectionProperty(name="Cost Value Attributes", type=Attribute)
cost_column: StringProperty(name="Cost Column")
should_show_column_ui: BoolProperty(name="Should Show Column UI", default=False)
columns: CollectionProperty(name="Columns", type=StrProperty)
active_column_index: IntProperty(name="Active Column Index")
@@ -13,7 +13,8 @@ class BIM_PT_cost_schedules(Panel):
@classmethod
def poll(cls, context):
return IfcStore.get_file()
file = IfcStore.get_file()
return file and hasattr(file, "schema") and file.schema != "IFC2X3"
def draw(self, context):
self.props = context.scene.BIMCostProperties
@@ -34,6 +35,7 @@ class BIM_PT_cost_schedules(Panel):
if self.props.active_cost_schedule_id and self.props.active_cost_schedule_id == cost_schedule_id:
op = row.operator("bim.select_cost_schedule_products", icon="RESTRICT_SELECT_OFF", text="")
op.cost_schedule = cost_schedule_id
row.prop(self.props, "should_show_column_ui", text="", icon="SHORTDISPLAY")
if self.props.is_editing == "COST_SCHEDULE":
row.operator("bim.edit_cost_schedule", text="", icon="CHECKMARK")
elif self.props.is_editing == "COST_ITEMS":
@@ -52,8 +54,16 @@ class BIM_PT_cost_schedules(Panel):
if self.props.is_editing == "COST_SCHEDULE":
self.draw_editable_cost_schedule_ui()
elif self.props.is_editing == "COST_ITEMS":
if self.props.should_show_column_ui:
self.draw_column_ui()
self.draw_editable_cost_item_ui(cost_schedule_id)
def draw_column_ui(self):
row = self.layout.row(align=True)
row.prop(self.props, "cost_column", text="")
row.operator("bim.add_cost_column", text="", icon="ADD").name = self.props.cost_column
self.layout.template_list("BIM_UL_cost_columns", "", self.props, "columns", self.props, "active_column_index")
def draw_editable_cost_schedule_ui(self):
for attribute in self.props.cost_schedule_attributes:
row = self.layout.row(align=True)
@@ -164,7 +174,6 @@ class BIM_PT_cost_schedules(Panel):
box = self.layout.box()
self.draw_editable_cost_value_ui(box, Data.cost_values[self.props.active_cost_item_value_id])
def draw_readonly_cost_value_ui(self, layout, cost_value_id):
cost_value = Data.cost_values[cost_value_id]
cost_value_label = "{0:.2f}".format(cost_value["AppliedValue"])
@@ -235,7 +244,6 @@ class BIM_PT_cost_schedules(Panel):
row.prop(attribute, "is_null", icon="RADIOBUT_OFF" if attribute.is_null else "RADIOBUT_ON", text="")
class BIM_UL_cost_items(UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if item:
@@ -262,11 +270,15 @@ class BIM_UL_cost_items(UIList):
op = row.operator("bim.enable_editing_cost_item_quantities", text="", icon="PROPERTIES")
op.cost_item = item.ifc_definition_id
row.label(text="{0:.2f}".format(cost_item["TotalCostQuantity"]) + " (M3)")
row.label(text="{0:.2f}".format(cost_item["TotalCostQuantity"]) + f" ({cost_item['UnitSymbol']})")
op = row.operator("bim.enable_editing_cost_item_values", text="", icon="DISC")
op.cost_item = item.ifc_definition_id
row.label(text="{0:.2f}".format(cost_item["TotalAppliedValue"]))
for column in props.columns:
row.label(text=str(cost_item["CategoryValues"].get(column.name, "-")))
row.label(text="{0:.2f}".format(cost_item["TotalCostValue"]), icon="CON_TRANSLIKE")
if context.active_object:
@@ -298,3 +310,12 @@ class BIM_UL_cost_items(UIList):
).cost_item = item.ifc_definition_id
row.operator("bim.add_cost_item", text="", icon="ADD").cost_item = item.ifc_definition_id
row.operator("bim.remove_cost_item", text="", icon="X").cost_item = item.ifc_definition_id
class BIM_UL_cost_columns(UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
props = context.scene.BIMCostProperties
if item:
row = layout.row(align=True)
row.prop(item, "name", emboss=False, text="")
row.operator("bim.remove_cost_column", text="", icon="X").name = item.name
@@ -16,13 +16,13 @@ class Login(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
token = api.login(bpy.context.scene.CoveToolProperties.username, bpy.context.scene.CoveToolProperties.password)
token = api.login(context.scene.CoveToolProperties.username, context.scene.CoveToolProperties.password)
if token:
bpy.context.scene.CoveToolProperties.token = token
context.scene.CoveToolProperties.token = token
projects = api.get_request("projects")
for project in projects:
new_project = bpy.context.scene.CoveToolProperties.projects.add()
new_project = context.scene.CoveToolProperties.projects.add()
new_project.name = project["name"]
new_project.run_set = project["run_set"][0]
new_project.url = project["url"]
@@ -36,10 +36,10 @@ class RunSimpleAnalysis(bpy.types.Operator):
bl_label = "Run Simple Analysis"
def execute(self, context):
simple_analysis = bpy.context.scene.CoveToolProperties.simple_analysis
simple_analysis = context.scene.CoveToolProperties.simple_analysis
data = {
"run": bpy.context.scene.CoveToolProperties.projects[
bpy.context.scene.CoveToolProperties.active_project_index
"run": context.scene.CoveToolProperties.projects[
context.scene.CoveToolProperties.active_project_index
].run_set,
"si_units": simple_analysis.si_units,
"building_height": simple_analysis.building_height,
@@ -84,10 +84,10 @@ class RunAnalysis(bpy.types.Operator):
"roofs": [],
"shading_devices": [],
}
self.parse_objects()
self.parse_objects(context)
data = {
"run": bpy.context.scene.CoveToolProperties.projects[
bpy.context.scene.CoveToolProperties.active_project_index
"run": context.scene.CoveToolProperties.projects[
context.scene.CoveToolProperties.active_project_index
].run_set,
"source": "BlenderBIM",
"rotation_angle": self.get_rotation_angle(),
@@ -112,14 +112,14 @@ class RunAnalysis(bpy.types.Operator):
rotation = 360 - rotation
return rotation
def parse_objects(self):
for obj in bpy.context.visible_objects:
def parse_objects(self, context):
for obj in context.visible_objects:
covetool_category = self.get_covetool_category(obj)
if not covetool_category:
continue
if not self.has_triangulate_modifier(obj):
obj.modifiers.new(name="Triangulate", type="TRIANGULATE")
mesh = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()
mesh = obj.evaluated_get(context.evaluated_depsgraph_get()).to_mesh()
meshes = {}
for polygon in mesh.polygons:
normal = "{}|{}|{}".format(
@@ -197,5 +197,4 @@ class RunAnalysis(bpy.types.Operator):
return True
def is_window_skylight(self, element):
predefined_type = element.get_info().get("PredefinedType")
return predefined_type and predefined_type.string_value == "SKYLIGHT"
return element.get_info().get("PredefinedType") == "SKYLIGHT"
@@ -3,6 +3,8 @@ from . import ui, prop, operator
classes = (
operator.PrintIfcFile,
operator.PurgeIfcLinks,
operator.PrintObjectPlacement,
operator.ValidateIfcFile,
operator.ProfileImportIFC,
operator.CreateAllShapes,
@@ -1,6 +1,9 @@
import bpy
import logging
import ifcopenshell
import ifcopenshell.util.placement
import ifcopenshell.util.representation
import blenderbim.bim.handler
import blenderbim.bim.import_ifc as import_ifc
from blenderbim.bim.ifc import IfcStore
@@ -9,15 +12,42 @@ class PrintIfcFile(bpy.types.Operator):
bl_idname = "bim.print_ifc_file"
bl_label = "Print IFC File"
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def execute(self, context):
print(IfcStore.get_file().wrapped_data.to_string())
return {"FINISHED"}
class PurgeIfcLinks(bpy.types.Operator):
bl_idname = "bim.purge_ifc_links"
bl_label = "Purge IFC Links"
def execute(self, context):
for obj in bpy.data.objects:
if obj.type in {"MESH", "EMPTY"}:
obj.BIMObjectProperties.ifc_definition_id = 0
if obj.data:
obj.data.BIMMeshProperties.ifc_definition_id = 0
for material in bpy.data.materials:
material.BIMMaterialProperties.ifc_style_id = False
context.scene.BIMProperties.ifc_file = ""
context.scene.BIMDebugProperties.attributes.clear()
IfcStore.purge()
blenderbim.bim.handler.purge_module_data()
return {"FINISHED"}
class ValidateIfcFile(bpy.types.Operator):
bl_idname = "bim.validate_ifc_file"
bl_label = "Validate IFC File"
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def execute(self, context):
import ifcopenshell.validate
@@ -31,16 +61,18 @@ class ProfileImportIFC(bpy.types.Operator):
bl_idname = "bim.profile_import_ifc"
bl_label = "Profile Import IFC"
@classmethod
def poll(cls, context):
return IfcStore.get_file() and context.scene.BIMProperties.ifc_file
def execute(self, context):
import cProfile
import pstats
# For Windows
filepath = bpy.context.scene.BIMProperties.ifc_file.replace('\\', '\\\\')
filepath = context.scene.BIMProperties.ifc_file.replace("\\", "\\\\")
cProfile.run(
f"import bpy; bpy.ops.import_ifc.bim(filepath='{filepath}')", "blender.prof"
)
cProfile.run(f"import bpy; bpy.ops.import_ifc.bim(filepath='{filepath}')", "blender.prof")
p = pstats.Stats("blender.prof")
p.sort_stats("cumulative").print_stats(50)
return {"FINISHED"}
@@ -50,24 +82,28 @@ class CreateAllShapes(bpy.types.Operator):
bl_idname = "bim.create_all_shapes"
bl_label = "Create All Shapes"
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def execute(self, context):
self.file = IfcStore.get_file()
elements = self.file.by_type("IfcElement") + self.file.by_type("IfcSpace")
total = len(elements)
settings = ifcopenshell.geom.settings()
failures = []
excludes = () # For the developer to debug with
excludes = () # For the developer to debug with
for i, element in enumerate(elements):
if element.GlobalId in excludes:
continue
print(f'{i}/{total}:', element)
print(f"{i}/{total}:", element)
try:
shape = ifcopenshell.geom.create_shape(settings, element)
print("Success", len(shape.geometry.verts), len(shape.geometry.edges), len(shape.geometry.faces))
except:
failures.append(element)
print('***** FAILURE *****')
print('Failures:')
print("***** FAILURE *****")
print("Failures:")
for failure in failures:
print(failure)
return {"FINISHED"}
@@ -77,23 +113,29 @@ class CreateShapeFromStepId(bpy.types.Operator):
bl_idname = "bim.create_shape_from_step_id"
bl_label = "Create Shape From STEP ID"
bl_options = {"REGISTER", "UNDO"}
should_include_curves: bpy.props.BoolProperty()
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
logger = logging.getLogger("ImportIFC")
self.ifc_import_settings = import_ifc.IfcImportSettings.factory(bpy.context, IfcStore.path, logger)
self.ifc_import_settings = import_ifc.IfcImportSettings.factory(context, IfcStore.path, logger)
self.file = IfcStore.get_file()
element = self.file.by_id(int(bpy.context.scene.BIMDebugProperties.step_id))
element = self.file.by_id(int(context.scene.BIMDebugProperties.step_id))
settings = ifcopenshell.geom.settings()
# settings.set(settings.INCLUDE_CURVES, True)
if self.should_include_curves:
settings.set(settings.INCLUDE_CURVES, True)
shape = ifcopenshell.geom.create_shape(settings, element)
ifc_importer = import_ifc.IfcImporter(self.ifc_import_settings)
ifc_importer.file = self.file
mesh = ifc_importer.create_mesh(element, shape)
obj = bpy.data.objects.new("Debug", mesh)
bpy.context.scene.collection.objects.link(obj)
context.scene.collection.objects.link(obj)
return {"FINISHED"}
@@ -103,17 +145,9 @@ class SelectHighPolygonMeshes(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
results = {}
for obj in bpy.data.objects:
if not isinstance(obj.data, bpy.types.Mesh) or len(obj.data.polygons) < int(
bpy.context.scene.BIMDebugProperties.number_of_polygons
):
continue
try:
obj.select_set(True)
except:
# If it is not in the view layer
pass
[o.select_set(True) for o in context.view_layer.objects
if o.type == 'MESH'
and len(o.data.polygons) > context.scene.BIMDebugProperties.number_of_polygons]
return {"FINISHED"}
@@ -122,7 +156,7 @@ class RewindInspector(bpy.types.Operator):
bl_label = "Rewind Inspector"
def execute(self, context):
props = bpy.context.scene.BIMDebugProperties
props = context.scene.BIMDebugProperties
total_breadcrumbs = len(props.step_id_breadcrumb)
if total_breadcrumbs < 2:
return {"FINISHED"}
@@ -138,20 +172,24 @@ class InspectFromStepId(bpy.types.Operator):
bl_label = "Inspect From STEP ID"
step_id: bpy.props.IntProperty()
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def execute(self, context):
self.file = IfcStore.get_file()
bpy.context.scene.BIMDebugProperties.active_step_id = self.step_id
crumb = bpy.context.scene.BIMDebugProperties.step_id_breadcrumb.add()
context.scene.BIMDebugProperties.active_step_id = self.step_id
crumb = context.scene.BIMDebugProperties.step_id_breadcrumb.add()
crumb.name = str(self.step_id)
element = self.file.by_id(self.step_id)
while len(bpy.context.scene.BIMDebugProperties.attributes) > 0:
bpy.context.scene.BIMDebugProperties.attributes.remove(0)
while len(bpy.context.scene.BIMDebugProperties.inverse_attributes) > 0:
bpy.context.scene.BIMDebugProperties.inverse_attributes.remove(0)
while len(bpy.context.scene.BIMDebugProperties.inverse_references) > 0:
bpy.context.scene.BIMDebugProperties.inverse_references.remove(0)
while len(context.scene.BIMDebugProperties.attributes) > 0:
context.scene.BIMDebugProperties.attributes.remove(0)
while len(context.scene.BIMDebugProperties.inverse_attributes) > 0:
context.scene.BIMDebugProperties.inverse_attributes.remove(0)
while len(context.scene.BIMDebugProperties.inverse_references) > 0:
context.scene.BIMDebugProperties.inverse_references.remove(0)
for key, value in element.get_info().items():
self.add_attribute(bpy.context.scene.BIMDebugProperties.attributes, key, value)
self.add_attribute(context.scene.BIMDebugProperties.attributes, key, value)
for key in dir(element):
if (
not key[0].isalpha()
@@ -160,9 +198,9 @@ class InspectFromStepId(bpy.types.Operator):
or not getattr(element, key)
):
continue
self.add_attribute(bpy.context.scene.BIMDebugProperties.inverse_attributes, key, getattr(element, key))
self.add_attribute(context.scene.BIMDebugProperties.inverse_attributes, key, getattr(element, key))
for inverse in self.file.get_inverse(element):
new = bpy.context.scene.BIMDebugProperties.inverse_references.add()
new = context.scene.BIMDebugProperties.inverse_references.add()
new.string_value = str(inverse)
new.int_value = inverse.id()
return {"FINISHED"}
@@ -186,8 +224,18 @@ class InspectFromObject(bpy.types.Operator):
bl_label = "Inspect From Object"
def execute(self, context):
ifc_definition_id = bpy.context.active_object.BIMObjectProperties.ifc_definition_id
ifc_definition_id = context.active_object.BIMObjectProperties.ifc_definition_id
if not ifc_definition_id:
return {"FINISHED"}
bpy.ops.bim.inspect_from_step_id(step_id=ifc_definition_id)
return {"FINISHED"}
class PrintObjectPlacement(bpy.types.Operator):
bl_idname = "bim.print_object_placement"
bl_label = "Print Object Placement"
step_id: bpy.props.IntProperty()
def execute(self, context):
print(ifcopenshell.util.placement.get_local_placement(IfcStore.get_file().by_id(self.step_id)))
return {"FINISHED"}
@@ -14,7 +14,7 @@ from bpy.props import (
class BIMDebugProperties(PropertyGroup):
step_id: IntProperty(name="STEP ID")
number_of_polygons: IntProperty(name="Number of Polygons")
number_of_polygons: IntProperty(name="Number of Polygons", min=0)
active_step_id: IntProperty(name="STEP ID")
step_id_breadcrumb: CollectionProperty(name="STEP ID Breadcrumb", type=StrProperty)
attributes: CollectionProperty(name="Attributes", type=Attribute)
@@ -23,21 +23,23 @@ class BIM_PT_debug(Panel):
row = layout.row()
row.operator("bim.print_ifc_file")
row = layout.row()
row.operator("bim.purge_ifc_links")
row = layout.row()
row.operator("bim.create_all_shapes")
row = layout.row()
row.operator("bim.profile_import_ifc")
row = layout.row()
row = layout.split(factor=0.5, align=True)
row.operator("bim.create_shape_from_step_id").should_include_curves = False
row.operator("bim.create_shape_from_step_id", text="", icon="IPO_ELASTIC").should_include_curves = True
row.prop(props, "step_id", text="")
row = layout.row()
row.operator("bim.create_shape_from_step_id")
row = layout.row()
row.prop(props, "number_of_polygons", text="")
row = layout.row()
row = layout.split(factor=0.7, align=True)
row.operator("bim.select_high_polygon_meshes")
row.prop(props, "number_of_polygons", text="")
layout.label(text="Inspector:")
@@ -46,7 +48,7 @@ class BIM_PT_debug(Panel):
row.operator("bim.rewind_inspector", icon="FRAME_PREV", text="")
row.prop(props, "active_step_id", text="")
row = layout.row(align=True)
row.operator("bim.inspect_from_step_id").step_id = bpy.context.scene.BIMDebugProperties.active_step_id
row.operator("bim.inspect_from_step_id").step_id = context.scene.BIMDebugProperties.active_step_id
row.operator("bim.inspect_from_object")
if props.attributes:
@@ -59,6 +61,9 @@ class BIM_PT_debug(Panel):
if attribute.name == "GlobalId":
op = row.operator("bim.select_global_id", icon="RESTRICT_SELECT_OFF", text="")
op.global_id = attribute.string_value
if attribute.name == "ObjectPlacement":
op = row.operator("bim.print_object_placement", icon="TRACKER", text="")
op.step_id = attribute.int_value
if attribute.int_value:
row.operator(
"bim.inspect_from_step_id", icon="DISCLOSURE_TRI_RIGHT", text=""
@@ -13,7 +13,7 @@ class SelectDiffJsonFile(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.DiffProperties.diff_json_file = self.filepath
context.scene.DiffProperties.diff_json_file = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -29,20 +29,20 @@ class VisualiseDiff(bpy.types.Operator):
def execute(self, context):
#ifc_file = IfcStore.get_file() # In case we get from Store
ifc_file = ifcopenshell.open(context.scene.DiffProperties.diff_new_file) # for Now refer to the new file
with open(bpy.context.scene.DiffProperties.diff_json_file, "r") as file:
with open(context.scene.DiffProperties.diff_json_file, "r") as file:
diff = json.load(file)
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
obj.color = (1.0, 1.0, 1.0, 0.2)
global_id = ifc_file.by_id(obj.BIMObjectProperties.ifc_definition_id).GlobalId
if not global_id:
continue
if global_id.string_value in diff["deleted"]:
if global_id in diff["deleted"]:
obj.color = (1.0, 0.0, 0.0, 0.2)
elif global_id.string_value in diff["added"]:
elif global_id in diff["added"]:
obj.color = (0.0, 1.0, 0.0, 0.2)
elif global_id.string_value in diff["changed"]:
elif global_id in diff["changed"]:
obj.color = (0.0, 0.0, 1.0, 0.2)
area = next(area for area in bpy.context.screen.areas if area.type == "VIEW_3D")
area = next(area for area in context.screen.areas if area.type == "VIEW_3D")
area.spaces[0].shading.color_type = "OBJECT"
return {"FINISHED"}
@@ -54,7 +54,7 @@ class SelectDiffOldFile(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.DiffProperties.diff_old_file = self.filepath
context.scene.DiffProperties.diff_old_file = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -69,7 +69,7 @@ class SelectDiffNewFile(bpy.types.Operator):
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
bpy.context.scene.DiffProperties.diff_new_file = self.filepath
context.scene.DiffProperties.diff_new_file = self.filepath
return {"FINISHED"}
def invoke(self, context, event):
@@ -93,12 +93,12 @@ class ExecuteIfcDiff(bpy.types.Operator):
import ifcdiff
ifc_diff = ifcdiff.IfcDiff(
bpy.context.scene.DiffProperties.diff_old_file,
bpy.context.scene.DiffProperties.diff_new_file,
context.scene.DiffProperties.diff_old_file,
context.scene.DiffProperties.diff_new_file,
self.filepath,
bpy.context.scene.DiffProperties.diff_relationships.split(),
context.scene.DiffProperties.diff_relationships.split(),
)
ifc_diff.diff()
ifc_diff.export()
bpy.context.scene.DiffProperties.diff_json_file = self.filepath
context.scene.DiffProperties.diff_json_file = self.filepath
return {"FINISHED"}
@@ -16,13 +16,13 @@ class Annotator:
return float(sizes[str(size)])
@staticmethod
def add_text(related_element=None):
def add_text(context, related_element=None):
curve = bpy.data.curves.new(type="FONT", name="Text")
curve.body = "TEXT"
obj = bpy.data.objects.new("Text", curve)
obj.matrix_world = bpy.context.scene.camera.matrix_world
obj.matrix_world = context.scene.camera.matrix_world
if related_element is None:
location, _, _, _ = Annotator.get_placeholder_coords()
location, _, _, _ = Annotator.get_placeholder_coords(context)
else:
obj.data.BIMTextProperties.related_element = related_element
location = related_element.location
@@ -31,12 +31,12 @@ class Annotator:
font = bpy.data.fonts.get("OpenGost TypeB TT")
if not font:
font = bpy.data.fonts.load(
os.path.join(bpy.context.scene.BIMProperties.data_dir, "fonts", "OpenGost Type B TT.ttf")
os.path.join(context.scene.BIMProperties.data_dir, "fonts", "OpenGost Type B TT.ttf")
)
font.name = "OpenGost Type B TT"
obj.data.font = font
obj.data.BIMTextProperties.font_size = "2.5"
collection = bpy.context.scene.camera.users_collection[0]
collection = context.scene.camera.users_collection[0]
collection.objects.link(obj)
Annotator.resize_text(obj)
return obj
@@ -64,9 +64,9 @@ class Annotator:
text_obj.data.size = font_size
@staticmethod
def add_line_to_annotation(obj, co1=None, co2=None):
def add_line_to_annotation(obj, context, co1=None, co2=None):
if co1 is None:
co1, co2, _, _ = Annotator.get_placeholder_coords()
co1, co2, _, _ = Annotator.get_placeholder_coords(context)
co1 = obj.matrix_world.inverted() @ co1
co2 = obj.matrix_world.inverted() @ co2
if isinstance(obj.data, bpy.types.Mesh):
@@ -83,8 +83,8 @@ class Annotator:
return obj
@staticmethod
def add_plane_to_annotation(obj):
co1, co2, co3, co4 = Annotator.get_placeholder_coords()
def add_plane_to_annotation(obj, context):
co1, co2, co3, co4 = Annotator.get_placeholder_coords(context)
co1 = obj.matrix_world.inverted() @ co1 # bot left
co2 = obj.matrix_world.inverted() @ co2 # top left
co3 = obj.matrix_world.inverted() @ co3 # bot right
@@ -132,8 +132,8 @@ class Annotator:
return obj
@staticmethod
def get_annotation_obj(name, data_type):
collection = bpy.context.scene.camera.users_collection[0]
def get_annotation_obj(name, data_type, context):
collection = context.scene.camera.users_collection[0]
for obj in collection.objects:
if name in obj.name:
return obj
@@ -148,13 +148,13 @@ class Annotator:
return obj
@staticmethod
def get_placeholder_coords():
camera = bpy.context.scene.camera
def get_placeholder_coords(context):
camera = context.scene.camera
z_offset = camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))
if bpy.context.scene.render.resolution_x > bpy.context.scene.render.resolution_y:
if context.scene.render.resolution_x > context.scene.render.resolution_y:
y = (
camera.data.ortho_scale
* (bpy.context.scene.render.resolution_y / bpy.context.scene.render.resolution_x)
* (context.scene.render.resolution_y / context.scene.render.resolution_x)
/ 4
)
else:
@@ -7,6 +7,9 @@ import bmesh
import shutil
import subprocess
import webbrowser
import multiprocessing
import ifcopenshell
import ifcopenshell.geom
import ifcopenshell.util.selector
import ifcopenshell.util.representation
import blenderbim.bim.module.drawing.svgwriter as svgwriter
@@ -231,6 +234,39 @@ class CreateDrawing(bpy.types.Operator):
svg_path = os.path.join(context.scene.BIMProperties.data_dir, "cache", self.drawing_name + "-linework.svg")
if os.path.isfile(svg_path) and self.props.should_use_linework_cache:
return svg_path
# This is a work in progress. See #1153 and #1564.
# Switch from old to new if you are testing v0.7.0
self.generate_linework_old(context, svg_path)
# self.generate_linework_new(svg_path)
return svg_path
def generate_linework_new(self, svg_path):
settings = ifcopenshell.geom.settings(
APPLY_DEFAULT_MATERIALS=True,
DISABLE_TRIANGULATION=True,
INCLUDE_CURVES=True,
EXCLUDE_SOLIDS_AND_SURFACES=False,
)
buffer = ifcopenshell.geom.serializers.buffer()
serialiser = ifcopenshell.geom.serializers.svg(buffer, settings)
serialiser.setFile(self.file)
serialiser.setElevationRef("DRAWING")
serialiser.setUseNamespace(True)
serialiser.setAlwaysProject(True)
serialiser.setUseHlrPoly(True)
serialiser.setWithoutStoreys(True)
excluded_elements = []
for ifc_class in ["IfcSpace", "IfcOpeningElement", "IfcDoor", "IfcWindow"]:
excluded_elements += self.file.by_type(ifc_class)
for element in ifcopenshell.geom.iterate(
settings, self.file, multiprocessing.cpu_count(), exclude=excluded_elements
):
serialiser.write(element)
serialiser.finalize()
with open(svg_path, "w") as svg:
svg.write(buffer.get_value())
def generate_linework_old(self, context, svg_path):
ifcconvert_path = os.path.join(cwd, "..", "..", "..", "libs", "IfcConvert")
subprocess.run(
[
@@ -431,7 +467,7 @@ class AddAnnotation(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
if not bpy.context.scene.camera:
if not context.scene.camera:
return {"FINISHED"}
subcontext = ifcopenshell.util.representation.get_context(
IfcStore.get_file(), "Plan", "Annotation", context.scene.camera.data.BIMCameraProperties.target_view
@@ -439,17 +475,17 @@ class AddAnnotation(bpy.types.Operator):
if not subcontext:
return {"FINISHED"}
if self.data_type == "text":
if bpy.context.selected_objects:
for selected_object in bpy.context.selected_objects:
obj = annotation.Annotator.add_text(related_element=selected_object)
if context.selected_objects:
for selected_object in context.selected_objects:
obj = annotation.Annotator.add_text(context, related_element=selected_object)
else:
obj = annotation.Annotator.add_text()
obj = annotation.Annotator.add_text(context)
else:
obj = annotation.Annotator.get_annotation_obj(self.obj_name, self.data_type)
obj = annotation.Annotator.get_annotation_obj(self.obj_name, self.data_type, context)
if self.obj_name == "Break":
obj = annotation.Annotator.add_plane_to_annotation(obj)
obj = annotation.Annotator.add_plane_to_annotation(obj, context)
else:
obj = annotation.Annotator.add_line_to_annotation(obj)
obj = annotation.Annotator.add_line_to_annotation(obj, context)
if not obj.BIMObjectProperties.ifc_definition_id:
bpy.ops.bim.assign_class(obj=obj.name, ifc_class="IfcAnnotation", context_id=subcontext.id())
@@ -659,10 +695,10 @@ class GenerateReferences(bpy.types.Operator):
self.generate_grids()
if self.camera.data.BIMCameraProperties.target_view == "ELEVATION_VIEW":
self.generate_grids()
self.generate_levels()
self.generate_levels(context)
if self.camera.data.BIMCameraProperties.target_view == "SECTION_VIEW":
self.generate_grids()
self.generate_levels()
self.generate_levels(context)
return {"FINISHED"}
def filter_potential_references(self):
@@ -678,7 +714,7 @@ class GenerateReferences(bpy.types.Operator):
# TODO
pass
def generate_levels(self):
def generate_levels(self, context):
if self.camera.data.BIMCameraProperties.raster_x > self.camera.data.BIMCameraProperties.raster_y:
width = self.camera.data.ortho_scale
height = (
@@ -689,7 +725,7 @@ class GenerateReferences(bpy.types.Operator):
width = (
height / self.camera.data.BIMCameraProperties.raster_y * self.camera.data.BIMCameraProperties.raster_x
)
level_obj = annotation.Annotator.get_annotation_obj("Section Level", "curve")
level_obj = annotation.Annotator.get_annotation_obj("Section Level", "curve", context)
width_in_mm = width * 1000
if self.camera.data.BIMCameraProperties.diagram_scale == "CUSTOM":
@@ -706,7 +742,7 @@ class GenerateReferences(bpy.types.Operator):
projection = self.project_point_onto_camera(obj.location)
co1 = self.camera.matrix_world @ Vector((width / 2 - (offset_percentage * width), projection[1], -1))
co2 = self.camera.matrix_world @ Vector((-(width / 2), projection[1], -1))
annotation.Annotator.add_line_to_annotation(level_obj, co1, co2)
annotation.Annotator.add_line_to_annotation(level_obj, context, co1, co2)
def project_point_onto_camera(self, point):
projection = self.camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))
@@ -28,7 +28,7 @@ class External(svgwrite.container.Group):
# Remove namespace
ns = u"{http://www.w3.org/2000/svg}"
nsl = len(ns)
for elem in self.xml.getiterator():
for elem in self.xml.iter():
if elem.tag.startswith(ns):
elem.tag = elem.tag[nsl:]
@@ -85,19 +85,19 @@ class SvgWriter:
def add_markers(self):
tree = ET.parse(os.path.join(self.data_dir, "templates", "markers.svg"))
root = tree.getroot()
for child in root.getchildren():
for child in root:
self.svg.defs.add(External(child))
def add_symbols(self):
tree = ET.parse(os.path.join(self.data_dir, "templates", "symbols.svg"))
root = tree.getroot()
for child in root.getchildren():
for child in root:
self.svg.defs.add(External(child))
def add_patterns(self):
tree = ET.parse(os.path.join(self.data_dir, "templates", "patterns.svg"))
root = tree.getroot()
for child in root.getchildren():
for child in root:
self.svg.defs.add(External(child))
def draw_background_image(self):
@@ -24,7 +24,7 @@ class BIM_PT_camera(Panel):
return
layout.use_property_split = True
dprops = bpy.context.scene.DocProperties
dprops = context.scene.DocProperties
props = context.active_object.data.BIMCameraProperties
col = layout.column(align=True)
@@ -92,7 +92,7 @@ class BIM_PT_drawing_underlay(Panel):
def draw(self, context):
layout = self.layout
layout.use_property_split = True
dprops = bpy.context.scene.DocProperties
dprops = context.scene.DocProperties
props = context.active_object.data.BIMCameraProperties
row = layout.row(align=True)
@@ -142,7 +142,7 @@ class BIM_PT_drawings(Panel):
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = bpy.context.scene.DocProperties
props = context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_drawing")
@@ -175,7 +175,7 @@ class BIM_PT_schedules(Panel):
def draw(self, context):
layout = self.layout
layout.use_property_split = True
props = bpy.context.scene.DocProperties
props = context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_schedule")
@@ -200,7 +200,7 @@ class BIM_PT_sheets(Panel):
def draw(self, context):
layout = self.layout
props = bpy.context.scene.DocProperties
props = context.scene.DocProperties
row = layout.row(align=True)
row.prop(props, "titleblock", text="")
@@ -315,7 +315,7 @@ class BIM_PT_annotation_utilities(Panel):
op.obj_name = "Misc"
op.data_type = "mesh"
props = bpy.context.scene.DocProperties
props = context.scene.DocProperties
row = layout.row(align=True)
row.operator("bim.add_drawing")
@@ -24,10 +24,10 @@ class EditObjectPlacement(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
objs = [bpy.data.objects.get(self.obj)] if self.obj else bpy.context.selected_objects
objs = [bpy.data.objects.get(self.obj)] if self.obj else context.selected_objects
self.file = IfcStore.get_file()
# TODO: determine how to deal with this module dependency
props = bpy.context.scene.BIMGeoreferenceProperties
props = context.scene.BIMGeoreferenceProperties
for obj in objs:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
@@ -69,7 +69,7 @@ class AddRepresentation(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
bpy.ops.bim.edit_object_placement(obj=obj.name)
@@ -79,7 +79,7 @@ class AddRepresentation(bpy.types.Operator):
product = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
context_id = self.context_id or int(bpy.context.scene.BIMProperties.contexts)
context_id = self.context_id or int(context.scene.BIMProperties.contexts)
context_of_items = self.file.by_id(context_id)
gprop = context.scene.BIMGeoreferenceProperties
@@ -117,19 +117,20 @@ class AddRepresentation(bpy.types.Operator):
if s.material and not s.material.BIMMaterialProperties.ifc_style_id
]
ifcopenshell.api.run(
"style.assign_representation_styles",
self.file,
**{
"shape_representation": result,
"styles": [
self.file.by_id(s.material.BIMMaterialProperties.ifc_style_id)
for s in obj.material_slots
if s.material
],
"should_use_presentation_style_assignment": context.scene.BIMGeometryProperties.should_use_presentation_style_assignment,
},
)
if isinstance(obj.data, bpy.types.Mesh) and len(obj.data.polygons):
ifcopenshell.api.run(
"style.assign_representation_styles",
self.file,
**{
"shape_representation": result,
"styles": [
self.file.by_id(s.material.BIMMaterialProperties.ifc_style_id)
for s in obj.material_slots
if s.material
],
"should_use_presentation_style_assignment": context.scene.BIMGeometryProperties.should_use_presentation_style_assignment,
},
)
ifcopenshell.api.run(
"geometry.assign_representation", self.file, **{"product": product, "representation": result}
)
@@ -160,9 +161,10 @@ class SwitchRepresentation(bpy.types.Operator):
ifc_definition_id: bpy.props.IntProperty()
should_reload: bpy.props.BoolProperty()
disable_opening_subtractions: bpy.props.BoolProperty()
should_switch_all_meshes: bpy.props.BoolProperty()
def execute(self, context):
self.element_obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
self.element_obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.oprops = self.element_obj.BIMObjectProperties
self.file = IfcStore.get_file()
@@ -171,11 +173,17 @@ class SwitchRepresentation(bpy.types.Operator):
mesh = bpy.data.meshes.get(self.mesh_name)
if mesh:
self.element_obj.data.user_remap(mesh)
self.switch_mesh(mesh)
if not mesh or self.should_reload:
self.pull_mesh_from_ifc()
self.pull_mesh_from_ifc(context)
return {"FINISHED"}
def switch_mesh(self, mesh):
if self.should_switch_all_meshes or self.file.by_id(self.oprops.ifc_definition_id).is_a("IfcTypeProduct"):
self.element_obj.data.user_remap(mesh)
else:
self.element_obj.data = mesh
def get_mesh_name(self):
representation = self.resolve_mapped_representation(self.file.by_id(self.ifc_definition_id))
return "{}/{}".format(self.context_of_items.id(), representation.id())
@@ -185,9 +193,9 @@ class SwitchRepresentation(bpy.types.Operator):
return self.resolve_mapped_representation(representation.Items[0].MappingSource.MappedRepresentation)
return representation
def pull_mesh_from_ifc(self):
def pull_mesh_from_ifc(self, context):
logger = logging.getLogger("ImportIFC")
ifc_import_settings = import_ifc.IfcImportSettings.factory(bpy.context, IfcStore.path, logger)
ifc_import_settings = import_ifc.IfcImportSettings.factory(context, IfcStore.path, logger)
element = self.file.by_id(self.oprops.ifc_definition_id)
settings = ifcopenshell.geom.settings()
@@ -205,7 +213,7 @@ class SwitchRepresentation(bpy.types.Operator):
mesh = ifc_importer.create_mesh(element, shape)
mesh.name = self.mesh_name
mesh.BIMMeshProperties.ifc_definition_id = self.ifc_definition_id
self.element_obj.data.user_remap(mesh)
self.switch_mesh(mesh)
material_creator = import_ifc.MaterialCreator(ifc_import_settings, ifc_importer)
material_creator.load_existing_materials()
material_creator.create(element, self.element_obj, mesh)
@@ -239,7 +247,7 @@ class RemoveRepresentation(bpy.types.Operator):
def _execute(self, context):
self.file = IfcStore.get_file()
representation = self.file.by_id(self.representation_id)
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
is_mapped_representation = representation.RepresentationType == "MappedRepresentation"
if is_mapped_representation:
mesh_name = "{}/{}".format(
@@ -280,7 +288,7 @@ class UpdateRepresentation(bpy.types.Operator):
if not ContextData.is_loaded:
ContextData.load(IfcStore.get_file())
objs = [bpy.data.objects.get(self.obj)] if self.obj else bpy.context.selected_objects
objs = [bpy.data.objects.get(self.obj)] if self.obj else context.selected_objects
self.file = IfcStore.get_file()
for obj in objs:
@@ -330,19 +338,20 @@ class UpdateRepresentation(bpy.types.Operator):
if s.material and not s.material.BIMMaterialProperties.ifc_style_id
]
ifcopenshell.api.run(
"style.assign_representation_styles",
self.file,
**{
"shape_representation": new_representation,
"styles": [
self.file.by_id(s.material.BIMMaterialProperties.ifc_style_id)
for s in obj.material_slots
if s.material
],
"should_use_presentation_style_assignment": context.scene.BIMGeometryProperties.should_use_presentation_style_assignment,
},
)
if isinstance(obj.data, bpy.types.Mesh) and len(obj.data.polygons):
ifcopenshell.api.run(
"style.assign_representation_styles",
self.file,
**{
"shape_representation": new_representation,
"styles": [
self.file.by_id(s.material.BIMMaterialProperties.ifc_style_id)
for s in obj.material_slots
if s.material
],
"should_use_presentation_style_assignment": context.scene.BIMGeometryProperties.should_use_presentation_style_assignment,
},
)
# TODO: move this into a replace_representation usecase or something
for inverse in self.file.get_inverse(old_representation):
@@ -362,11 +371,13 @@ class UpdateParametricRepresentation(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
obj = bpy.context.active_object
obj = context.active_object
props = obj.data.BIMMeshProperties
parameter = props.ifc_parameters[self.index]
element = IfcStore.get_file().by_id(parameter.step_id)[parameter.index] = parameter.value
bpy.ops.bim.switch_representation(ifc_definition_id=props.ifc_definition_id, should_reload=True)
bpy.ops.bim.switch_representation(
ifc_definition_id=props.ifc_definition_id, should_reload=True, should_switch_all_meshes=True
)
return {"FINISHED"}
@@ -377,7 +388,7 @@ class GetRepresentationIfcParameters(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
obj = bpy.context.active_object
obj = context.active_object
props = obj.data.BIMMeshProperties
elements = IfcStore.get_file().traverse(IfcStore.get_file().by_id(props.ifc_definition_id))
for element in elements:
@@ -30,7 +30,7 @@ class BIM_PT_representations(Panel):
layout.label(text="No representations found")
row = layout.row(align=True)
row.prop(bpy.context.scene.BIMProperties, "contexts", text="")
row.prop(context.scene.BIMProperties, "contexts", text="")
row.operator("bim.add_representation", icon="ADD", text="")
for ifc_definition_id in representations:
@@ -41,6 +41,7 @@ class BIM_PT_representations(Panel):
row.label(text=representation["ContextOfItems"]["TargetView"])
row.label(text=representation["RepresentationType"])
op = row.operator("bim.switch_representation", icon="OUTLINER_DATA_MESH", text="")
op.should_switch_all_meshes = True
op.should_reload = True
op.ifc_definition_id = ifc_definition_id
op.disable_opening_subtractions = False
@@ -71,10 +72,12 @@ class BIM_PT_mesh(Panel):
row = layout.row(align=True)
op = row.operator("bim.switch_representation", text="Bake Voids", icon="SELECT_SUBTRACT")
op.should_switch_all_meshes=True
op.should_reload = True
op.ifc_definition_id = props.ifc_definition_id
op.disable_opening_subtractions = False
op = row.operator("bim.switch_representation", text="Dynamic Voids", icon="SELECT_INTERSECT")
op.should_switch_all_meshes=True
op.should_reload = True
op.ifc_definition_id = props.ifc_definition_id
op.disable_opening_subtractions = True
@@ -276,7 +276,7 @@ class ConvertLocalToGlobal(bpy.types.Operator):
results = (x, y, z)
props.coordinate_output = ",".join([str(r) for r in results])
bpy.context.scene.cursor.location = results
context.scene.cursor.location = results
return {"FINISHED"}
@@ -322,7 +322,7 @@ class ConvertGlobalToLocal(bpy.types.Operator):
props.coordinate_output = ",".join([str(r) for r in results])
scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
bpy.context.scene.cursor.location = [o * scale for o in results]
context.scene.cursor.location = [o * scale for o in results]
return {"FINISHED"}
@@ -334,7 +334,7 @@ class GetCursorLocation(bpy.types.Operator):
def execute(self, context):
props = context.scene.BIMGeoreferenceProperties
scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
project_coordinates = [o / scale for o in bpy.context.scene.cursor.location]
project_coordinates = [o / scale for o in context.scene.cursor.location]
props.coordinate_input = ",".join([str(o) for o in project_coordinates])
return {"FINISHED"}
@@ -347,5 +347,5 @@ class SetCursorLocation(bpy.types.Operator):
def execute(self, context):
props = context.scene.BIMGeoreferenceProperties
scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
bpy.context.scene.cursor.location = [float(co) * scale for co in props.coordinate_output.split(",")]
context.scene.cursor.location = [float(co) * scale for co in props.coordinate_output.split(",")]
return {"FINISHED"}
@@ -186,7 +186,7 @@ class SelectGroupProducts(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
for obj in bpy.context.visible_objects:
for obj in context.visible_objects:
obj.select_set(False)
if not obj.BIMObjectProperties.ifc_definition_id:
continue
@@ -2,6 +2,7 @@ import bpy
from . import ui, prop, operator
classes = (
operator.CopyMaterial,
operator.AddMaterial,
operator.RemoveMaterial,
operator.AssignMaterial,
@@ -1,6 +1,7 @@
import bpy
import json
import ifcopenshell.api
import ifcopenshell.util.element
import ifcopenshell.util.attribute
import ifcopenshell.util.representation
import blenderbim.bim.helper
@@ -22,7 +23,7 @@ class AssignParameterizedProfile(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
profile = ifcopenshell.api.run(
"profile.add_parameterized_profile",
@@ -50,18 +51,22 @@ class AddMaterial(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.materials.get(self.obj) if self.obj else bpy.context.active_object.active_material
obj = bpy.data.materials.get(self.obj) if self.obj else context.active_object.active_material
self.file = IfcStore.get_file()
result = ifcopenshell.api.run("material.add_material", self.file, **{"name": obj.name})
obj.BIMObjectProperties.ifc_definition_id = result.id()
IfcStore.link_element(result, obj)
if obj.BIMMaterialProperties.ifc_style_id:
context = ifcopenshell.util.representation.get_context(self.file, "Model", "Body", "MODEL_VIEW")
if context:
ifcopenshell.api.run("style.assign_material_style", self.file, **{
"material": result,
"style": self.file.by_id(obj.BIMMaterialProperties.ifc_style_id),
"context": context,
})
ifcopenshell.api.run(
"style.assign_material_style",
self.file,
**{
"material": result,
"style": self.file.by_id(obj.BIMMaterialProperties.ifc_style_id),
"context": context,
},
)
Data.load(IfcStore.get_file())
material_prop_purge()
return {"FINISHED"}
@@ -77,7 +82,7 @@ class RemoveMaterial(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.materials.get(self.obj) if self.obj else bpy.context.active_object.active_material
obj = bpy.data.materials.get(self.obj) if self.obj else context.active_object.active_material
self.file = IfcStore.get_file()
result = ifcopenshell.api.run(
"material.remove_material",
@@ -100,22 +105,40 @@ class AssignMaterial(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
material_type = self.material_type or obj.BIMObjectMaterialProperties.material_type
self.file = IfcStore.get_file()
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
ifcopenshell.api.run(
"material.assign_material",
self.file,
**{
"product": self.file.by_id(obj.BIMObjectProperties.ifc_definition_id),
"product": element,
"type": material_type,
"material": self.file.by_id(int(obj.BIMObjectMaterialProperties.material)),
},
)
Data.load(IfcStore.get_file())
Data.load(IfcStore.get_file(), obj.BIMObjectProperties.ifc_definition_id)
self.set_default_material(obj, element)
return {"FINISHED"}
def set_default_material(self, obj, element):
element_material = ifcopenshell.util.element.get_material(element)
material = [m for m in self.file.traverse(element_material) if m.is_a("IfcMaterial")]
if not material:
return
object_material_ids = [
om.BIMObjectProperties.ifc_definition_id
for om in obj.data.materials
if om is not None and om.BIMObjectProperties.ifc_definition_id
]
if material[0].id() in object_material_ids:
return
obj.data.materials.append(IfcStore.get_element(material[0].id()))
class UnassignMaterial(bpy.types.Operator):
bl_idname = "bim.unassign_material"
@@ -127,14 +150,14 @@ class UnassignMaterial(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.unassign_material",
self.file,
**{"product": self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)},
)
Data.load(IfcStore.get_file(), obj.BIMObjectProperties.ifc_definition_id)
Data.purge()
return {"FINISHED"}
@@ -149,7 +172,7 @@ class AddConstituent(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.add_constituent",
@@ -174,7 +197,7 @@ class RemoveConstituent(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.remove_constituent", self.file, **{"constituent": self.file.by_id(self.constituent)}
@@ -194,7 +217,7 @@ class AddProfile(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.add_profile",
@@ -205,6 +228,7 @@ class AddProfile(bpy.types.Operator):
},
)
Data.load_profiles()
ProfileData.load(self.file)
return {"FINISHED"}
@@ -219,10 +243,11 @@ class RemoveProfile(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run("material.remove_profile", self.file, **{"profile": self.file.by_id(self.profile)})
Data.load_profiles()
ProfileData.load(self.file)
return {"FINISHED"}
@@ -237,7 +262,7 @@ class AddLayer(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.add_layer",
@@ -264,7 +289,7 @@ class ReorderMaterialSetItem(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
material_set = self.file.by_id(self.material_set)
ifcopenshell.api.run(
@@ -282,6 +307,7 @@ class ReorderMaterialSetItem(bpy.types.Operator):
Data.load_layers()
elif material_set.is_a("IfcMaterialProfileSet"):
Data.load_profiles()
ProfileData.load(self.file)
elif material_set.is_a("IfcMaterialList"):
Data.load_lists()
return {"FINISHED"}
@@ -298,7 +324,7 @@ class RemoveLayer(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run("material.remove_layer", self.file, **{"layer": self.file.by_id(self.layer)})
Data.load_layers()
@@ -316,7 +342,7 @@ class AddListItem(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.add_list_item",
@@ -342,7 +368,7 @@ class RemoveListItem(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"material.remove_list_item",
@@ -363,7 +389,7 @@ class EnableEditingAssignedMaterial(bpy.types.Operator):
obj: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
props = obj.BIMObjectMaterialProperties
props.is_editing = True
product_data = Data.products[obj.BIMObjectProperties.ifc_definition_id]
@@ -451,7 +477,7 @@ class DisableEditingAssignedMaterial(bpy.types.Operator):
obj: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
props = obj.BIMObjectMaterialProperties
props.is_editing = False
return {"FINISHED"}
@@ -470,10 +496,9 @@ class EditAssignedMaterial(bpy.types.Operator):
def _execute(self, context):
self.file = IfcStore.get_file()
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
props = obj.BIMObjectMaterialProperties
product_data = Data.products[obj.BIMObjectProperties.ifc_definition_id]
material_set = self.file.by_id(self.material_set)
if product_data["type"] == "IfcMaterial":
bpy.ops.bim.unassign_material(obj=obj.name)
@@ -482,6 +507,8 @@ class EditAssignedMaterial(bpy.types.Operator):
bpy.ops.bim.disable_editing_assigned_material(obj=obj.name)
return {"FINISHED"}
material_set = self.file.by_id(self.material_set)
attributes = {}
for attribute in props.material_set_attributes:
attributes[attribute.name] = None if attribute.is_null else attribute.string_value
@@ -495,16 +522,21 @@ class EditAssignedMaterial(bpy.types.Operator):
if self.material_set_usage:
material_set_usage = self.file.by_id(self.material_set_usage)
attributes = blenderbim.bim.helper.export_attributes(props.material_set_usage_attributes)
if attributes.get("CardinalPoint", None):
attributes["CardinalPoint"] = int(attributes["CardinalPoint"])
ifcopenshell.api.run(
"material.edit_profile_usage",
self.file,
**{"usage": material_set_usage, "attributes": attributes},
)
if material_set_usage.is_a("IfcMaterialLayerSetUsage"):
ifcopenshell.api.run(
"material.edit_layer_usage",
self.file,
**{"usage": material_set_usage, "attributes": attributes},
)
Data.load_layer_usages()
elif material_set_usage.is_a("IfcMaterialProfileSetUsage"):
if attributes.get("CardinalPoint", None):
attributes["CardinalPoint"] = int(attributes["CardinalPoint"])
ifcopenshell.api.run(
"material.edit_profile_usage",
self.file,
**{"usage": material_set_usage, "attributes": attributes},
)
Data.load_profile_usages()
if material_set.is_a("IfcMaterialConstituentSet"):
@@ -514,8 +546,25 @@ class EditAssignedMaterial(bpy.types.Operator):
elif material_set.is_a("IfcMaterialProfileSet"):
Data.load_profiles()
bpy.ops.bim.disable_editing_assigned_material(obj=obj.name)
self.set_default_material(obj, self.file.by_id(obj.BIMObjectProperties.ifc_definition_id))
return {"FINISHED"}
def set_default_material(self, obj, element):
element_material = ifcopenshell.util.element.get_material(element)
material = [m for m in self.file.traverse(element_material) if m.is_a("IfcMaterial")]
if not material:
return
object_material_ids = [
om.BIMObjectProperties.ifc_definition_id
for om in obj.data.materials
if om is not None and om.BIMObjectProperties.ifc_definition_id
]
if material[0].id() in object_material_ids:
return
obj.data.materials.append(IfcStore.get_element(material[0].id()))
class EnableEditingMaterialSetItem(bpy.types.Operator):
bl_idname = "bim.enable_editing_material_set_item"
@@ -526,7 +575,7 @@ class EnableEditingMaterialSetItem(bpy.types.Operator):
def execute(self, context):
self.file = IfcStore.get_file()
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.props = obj.BIMObjectMaterialProperties
self.props.active_material_set_item_id = self.material_set_item
product_data = Data.products[obj.BIMObjectProperties.ifc_definition_id]
@@ -618,7 +667,7 @@ class DisableEditingMaterialSetItem(bpy.types.Operator):
obj: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
props = obj.BIMObjectMaterialProperties
props.active_material_set_item_id = 0
return {"FINISHED"}
@@ -635,7 +684,7 @@ class EditMaterialSetItem(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
obj = bpy.data.objects.get(self.obj) if self.obj else bpy.context.active_object
obj = bpy.data.objects.get(self.obj) if self.obj else context.active_object
self.file = IfcStore.get_file()
props = obj.BIMObjectMaterialProperties
product_data = Data.products[obj.BIMObjectProperties.ifc_definition_id]
@@ -705,3 +754,45 @@ class EditMaterialSetItem(bpy.types.Operator):
bpy.ops.bim.disable_editing_material_set_item(obj=obj.name)
return {"FINISHED"}
class CopyMaterial(bpy.types.Operator):
bl_idname = "bim.copy_material"
bl_label = "Copy Material"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
self.file = IfcStore.get_file()
material = ifcopenshell.util.element.get_material(
self.file.by_id(context.active_object.BIMObjectProperties.ifc_definition_id)
)
for obj in context.selected_objects:
if obj == context.active_object:
continue
if not obj.BIMObjectProperties.ifc_definition_id:
continue
ifcopenshell.api.run(
"material.copy_material",
self.file,
**{
"material": material,
"element": self.file.by_id(obj.BIMObjectProperties.ifc_definition_id),
},
)
Data.load(self.file, obj.BIMObjectProperties.ifc_definition_id)
self.set_default_material(obj, material)
return {"FINISHED"}
def set_default_material(self, obj, material):
object_material_ids = [
om.BIMObjectProperties.ifc_definition_id
for om in obj.data.materials
if om is not None and om.BIMObjectProperties.ifc_definition_id
]
if material.id() in object_material_ids:
return
obj.data.materials.append(IfcStore.get_element(material.id()))
@@ -49,6 +49,11 @@ def getParameterizedProfileClasses(self, context):
(t.name(), t.name(), "")
for t in IfcStore.get_schema().declaration_by_name("IfcParameterizedProfileDef").subtypes()
]
for ifc_class in parameterizedprofileclasses_enum:
parameterizedprofileclasses_enum.extend([
(t.name(), t.name(), "")
for t in IfcStore.get_schema().declaration_by_name(ifc_class[0]).subtypes() or []
])
return parameterizedprofileclasses_enum
@@ -97,6 +97,8 @@ class BIM_PT_object_material(Panel):
self.material_set_data = Data.lists[self.material_set_id]
self.set_items = self.material_set_data["Materials"] or []
self.set_item_name = "list_item"
else:
self.material_set_id = 0
return self.draw_material_ui()
row = self.layout.row(align=True)
@@ -116,6 +118,8 @@ class BIM_PT_object_material(Panel):
op.material_set_usage = self.product_data["id"]
row.operator("bim.disable_editing_assigned_material", icon="CANCEL", text="")
else:
if self.product_data["type"] == "IfcMaterial":
row.operator("bim.copy_material", icon="COPYDOWN", text="")
row.operator("bim.enable_editing_assigned_material", icon="GREASEPENCIL", text="")
row.operator("bim.unassign_material", icon="X", text="")
@@ -198,7 +202,9 @@ class BIM_PT_object_material(Panel):
row.prop(self.props, "profile_classes", text="")
if self.props.profile_classes == "IfcParameterizedProfileDef":
row.prop(self.props, "parameterized_profile_classes", text="")
op = row.operator("bim.assign_parameterized_profile", icon="GREASEPENCIL" if item["Profile"] else "ADD", text="")
op = row.operator(
"bim.assign_parameterized_profile", icon="GREASEPENCIL" if item["Profile"] else "ADD", text=""
)
op.ifc_class = self.props.parameterized_profile_classes
op.material_profile = item["id"]
else:
@@ -316,11 +322,11 @@ class BIM_PT_object_material(Panel):
item_name = item.get("Name", "Unnamed") or "Unnamed"
thickness = item.get("LayerThickness")
if thickness:
item_name += f" ({thickness})"
item_name += f" ({thickness:.3f})"
total_thickness += thickness
row.label(text=item_name, icon="ALIGN_CENTER")
row.label(text=Data.materials[item["Material"]]["Name"], icon="MATERIAL")
if total_thickness:
row = self.layout.row(align=True)
row.label(text=f"Total Thickness: {total_thickness}")
row.label(text=f"Total Thickness: {total_thickness:.3f}")
@@ -3,11 +3,16 @@ from . import handler, prop, ui, grid, product, wall, slab, stair, door, window,
classes = (
product.AddTypeInstance,
wall.AddWall,
product.AlignProduct,
product.DynamicallyVoidProduct,
workspace.Hotkey,
wall.JoinWall,
wall.AlignWall,
wall.FlipWall,
wall.SplitWall,
wall.AddWallOpening,
slab.AddSlabOpening,
profile.ExtendProfile,
prop.BIMModelProperties,
ui.BIM_PT_authoring,
ui.BIM_PT_authoring_architectural,
@@ -28,7 +33,8 @@ addon_keymaps = []
def register():
bpy.utils.register_tool(workspace.BimTool, after={"builtin.scale_cage"}, separator=True, group=True)
if not bpy.app.background:
bpy.utils.register_tool(workspace.BimTool, after={"builtin.scale_cage"}, separator=True, group=True)
bpy.types.Scene.BIMModelProperties = bpy.props.PointerProperty(type=prop.BIMModelProperties)
bpy.types.VIEW3D_MT_mesh_add.append(grid.add_object_button)
bpy.types.VIEW3D_MT_mesh_add.append(stair.add_object_button)
@@ -45,7 +51,8 @@ def register():
def unregister():
bpy.utils.unregister_tool(workspace.BimTool)
if not bpy.app.background:
bpy.utils.unregister_tool(workspace.BimTool)
del bpy.types.Scene.BIMModelProperties
bpy.app.handlers.load_post.remove(handler.load_post)
bpy.types.VIEW3D_MT_mesh_add.remove(grid.add_object_button)
@@ -1,168 +0,0 @@
import bpy
import bmesh
import math
import ifcopenshell
import ifcopenshell.util.type
import ifcopenshell.util.unit
import ifcopenshell.util.element
import mathutils.geometry
import blenderbim.bim.handler
from blenderbim.bim.ifc import IfcStore
from math import pi, degrees
from mathutils import Vector, Matrix
from ifcopenshell.api.pset.data import Data as PsetData
from ifcopenshell.api.material.data import Data as MaterialData
from blenderbim.bim.module.geometry.helper import Helper
def element_listener(element, obj):
blenderbim.bim.handler.subscribe_to(obj, "mode", mode_callback)
def mode_callback(obj, data):
for obj in bpy.context.selected_objects + [bpy.context.active_object]:
if (
obj.mode != "EDIT"
or not obj.data
or not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve, bpy.types.TextCurve))
or not obj.BIMObjectProperties.ifc_definition_id
or not bpy.context.scene.BIMProjectProperties.is_authoring
):
return
product = IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbColumn":
return
IfcStore.edited_objs.add(obj)
bm = bmesh.from_edit_mesh(obj.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
bmesh.update_edit_mesh(obj.data)
bm.free()
def ensure_solid(usecase_path, ifc_file, settings):
product = ifc_file.by_id(settings["blender_object"].BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbColumn":
return
material = ifcopenshell.util.element.get_material(product)
if material and material.is_a("IfcMaterialProfileSetUsage"):
settings["profile_set_usage"] = material
else:
return
settings["ifc_representation_class"] = "IfcExtrudedAreaSolid/IfcMaterialProfileSetUsage"
class DumbColumnGenerator:
def __init__(self, relating_type):
self.relating_type = relating_type
def generate(self):
self.file = IfcStore.get_file()
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
material = ifcopenshell.util.element.get_material(self.relating_type)
if material and material.is_a("IfcMaterialProfileSet"):
self.profile_set = material
else:
return
self.collection = bpy.context.view_layer.active_layer_collection.collection
self.collection_obj = bpy.data.objects.get(self.collection.name)
self.length = 3
self.rotation = 0
self.location = Vector((0, 0, 0))
return self.derive_from_cursor()
def derive_from_cursor(self):
self.location = bpy.context.scene.cursor.location
return self.create_column()
def create_column(self):
# A cube
verts = [
Vector((-1, -1, -1)),
Vector((-1, -1, 1)),
Vector((-1, 1, -1)),
Vector((-1, 1, 1)),
Vector((1, -1, -1)),
Vector((1, -1, 1)),
Vector((1, 1, -1)),
Vector((1, 1, 1)),
]
edges = []
faces = [
[0, 2, 3, 1],
[2, 3, 7, 6],
[4, 5, 7, 6],
[0, 1, 5, 4],
[1, 3, 7, 5],
[0, 2, 6, 4],
]
mesh = bpy.data.meshes.new(name="Dumb Column")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Column", mesh)
obj.name = "Column"
obj.location = self.location
if self.collection_obj and self.collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = self.collection_obj.location[2]
self.collection.objects.link(obj)
bpy.ops.bim.assign_class(
obj=obj.name, ifc_class="IfcColumn", predefined_type="COLUMN", should_add_representation=False
)
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
bpy.ops.bim.assign_type(relating_type=self.relating_type.id(), related_object=obj.name)
profile_set_usage = ifcopenshell.util.element.get_material(element)
bpy.ops.bim.add_representation(
obj=obj.name,
context_id=ifcopenshell.util.representation.get_context(self.file, "Model", "Body", "MODEL_VIEW").id(),
ifc_representation_class="IfcExtrudedAreaSolid/IfcMaterialProfileSetUsage",
profile_set_usage=profile_set_usage.id(),
)
representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW")
bpy.ops.bim.switch_representation(obj=obj.name, ifc_definition_id=representation.id(), should_reload=True)
pset = ifcopenshell.api.run("pset.add_pset", self.file, product=element, name="EPset_Parametric")
ifcopenshell.api.run("pset.edit_pset", self.file, pset=pset, properties={"Engine": "BlenderBIM.DumbColumn"})
MaterialData.load(self.file)
obj.select_set(True)
return obj
class DumbColumnRegenerator:
def regenerate_from_profile(self, usecase_path, ifc_file, settings):
self.file = IfcStore.get_file()
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
profile = settings["profile"].Profile
if not profile:
return
for profile_set in [
mp.ToMaterialProfileSet[0] for mp in self.file.get_inverse(profile) if mp.is_a("IfcMaterialProfile")
]:
for inverse in ifc_file.get_inverse(profile_set):
if not inverse.is_a("IfcMaterialProfileSetUsage"):
continue
if ifc_file.schema == "IFC2X3":
for rel in ifc_file.get_inverse(inverse):
if not rel.is_a("IfcRelAssociatesMaterial"):
continue
for element in rel.RelatedObjects:
self.change_profile(element)
else:
for rel in inverse.AssociatedTo:
for element in rel.RelatedObjects:
self.change_profile(element)
def regenerate_from_type(self, usecase_path, ifc_file, settings):
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file)
new_material = ifcopenshell.util.element.get_material(settings["relating_type"])
if not new_material or not new_material.is_a("IfcMaterialProfileSet"):
return
self.change_profile(settings["related_object"])
def change_profile(self, element):
obj = IfcStore.get_element(element.id())
if not obj:
return
representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW")
if representation:
bpy.ops.bim.switch_representation(obj=obj.name, ifc_definition_id=representation.id(), should_reload=True)
@@ -82,7 +82,7 @@ def add_object(self, context):
obj = bpy.data.objects.new("Door Profile", mesh)
context.view_layer.active_layer_collection.collection.objects.link(obj)
bpy.context.view_layer.objects.active = obj
context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.convert(target="CURVE")
@@ -100,7 +100,7 @@ def add_object(self, context):
obj2 = bpy.data.objects.new("Door", mesh)
context.view_layer.active_layer_collection.collection.objects.link(obj2)
bpy.context.view_layer.objects.active = obj2
context.view_layer.objects.active = obj2
obj2.select_set(True)
bpy.ops.object.convert(target="CURVE")
@@ -130,11 +130,11 @@ def add_object(self, context):
modifier.thickness = self.overall_height - 0.045
context.view_layer.active_layer_collection.collection.objects.link(obj3)
bpy.context.view_layer.objects.active = obj3
context.view_layer.objects.active = obj3
obj3.select_set(True)
bpy.ops.object.convert(target="MESH")
ctx = bpy.context.copy()
ctx = context.copy()
ctx["active_object"] = obj2
ctx["selected_editable_objects"] = [obj2, obj3]
bpy.ops.object.join(ctx)
@@ -156,7 +156,7 @@ def add_object(self, context):
modifier.thickness = self.overall_height + 0.1
context.view_layer.active_layer_collection.collection.objects.link(obj4)
bpy.context.view_layer.objects.active = obj4
context.view_layer.objects.active = obj4
obj4.select_set(True)
bpy.ops.object.convert(target="MESH")
@@ -12,7 +12,7 @@ def add_object(self, context):
collection = bpy.data.collections.new(obj.name)
has_site_collection = False
for child in bpy.context.view_layer.layer_collection.children:
for child in context.view_layer.layer_collection.children:
if "IfcProject/" not in child.name:
continue
for grandchild in child.children:
@@ -22,7 +22,7 @@ def add_object(self, context):
grandchild.collection.children.link(collection)
break
if not has_site_collection:
bpy.context.view_layer.active_layer_collection.collection.children.link(collection)
context.view_layer.active_layer_collection.collection.children.link(collection)
collection.objects.link(obj)
self.file = IfcStore.get_file()
@@ -1,13 +1,17 @@
import bpy
import ifcopenshell
import ifcopenshell.api
from blenderbim.bim.module.model import product, wall, slab, column
from blenderbim.bim.module.model import root, product, wall, slab, profile, opening
from blenderbim.bim.ifc import IfcStore
from bpy.app.handlers import persistent
@persistent
def load_post(*args):
ifcopenshell.api.add_pre_listener(
"attribute.edit_attributes", "BlenderBIM.Root.SyncName", root.sync_name
)
ifcopenshell.api.add_post_listener(
"geometry.add_representation", "BlenderBIM.Product.GenerateBox", product.generate_box
)
@@ -17,6 +21,8 @@ def load_post(*args):
product.regenerate_profile_usage,
)
IfcStore.add_element_listener(opening.element_listener)
IfcStore.add_element_listener(wall.element_listener)
ifcopenshell.api.add_pre_listener(
"geometry.add_representation", "BlenderBIM.DumbWall.EnsureSolid", wall.ensure_solid
@@ -51,17 +57,22 @@ def load_post(*args):
"type.assign_type", "BlenderBIM.DumbSlab.RegenerateFromType", slab.DumbSlabPlaner().regenerate_from_type
)
IfcStore.add_element_listener(column.element_listener)
IfcStore.add_element_listener(profile.element_listener)
ifcopenshell.api.add_pre_listener(
"geometry.add_representation", "BlenderBIM.DumbColumn.EnsureSolid", column.ensure_solid
"geometry.add_representation", "BlenderBIM.DumbProfile.EnsureSolid", profile.ensure_solid
)
ifcopenshell.api.add_pre_listener(
"material.edit_profile",
"BlenderBIM.DumbProfile.SyncObjectFromProfile",
profile.DumbProfileRegenerator().sync_object_from_profile,
)
ifcopenshell.api.add_post_listener(
"material.edit_profile",
"BlenderBIM.DumbColumn.RegenerateFromProfile",
column.DumbColumnRegenerator().regenerate_from_profile,
"BlenderBIM.DumbProfile.RegenerateFromProfile",
profile.DumbProfileRegenerator().regenerate_from_profile,
)
ifcopenshell.api.add_post_listener(
"type.assign_type",
"BlenderBIM.DumbColumn.RegenerateFromType",
column.DumbColumnRegenerator().regenerate_from_type,
"BlenderBIM.DumbProfile.RegenerateFromType",
profile.DumbProfileRegenerator().regenerate_from_type,
)
@@ -1,10 +1,57 @@
import bpy
import bmesh
import blenderbim.bim.handler
import ifcopenshell
import ifcopenshell.util.representation
from blenderbim.bim.ifc import IfcStore
from math import pi
from bpy.types import Operator
from bpy.props import FloatProperty
from bpy_extras.object_utils import AddObjectHelper, object_data_add
def element_listener(element, obj):
blenderbim.bim.handler.subscribe_to(obj, "mode", mode_callback)
def mode_callback(obj, data):
for obj in set(bpy.context.selected_objects + [bpy.context.active_object]):
if (
obj.mode != "EDIT"
or not obj.data
or not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve, bpy.types.TextCurve))
or not obj.BIMObjectProperties.ifc_definition_id
or not bpy.context.scene.BIMProjectProperties.is_authoring
):
return
product = IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id)
if not product.is_a("IfcOpeningElement"):
return
for rel in product.VoidsElements:
building_element_obj = IfcStore.get_element(rel.RelatingBuildingElement.id())
if not building_element_obj:
continue
if [m for m in building_element_obj.modifiers if m.type == "BOOLEAN"]:
continue
representation = ifcopenshell.util.representation.get_representation(
rel.RelatingBuildingElement, "Model", "Body", "MODEL_VIEW"
)
if not representation:
continue
bpy.ops.bim.switch_representation(
obj=building_element_obj.name,
should_switch_all_meshes=True,
should_reload=True,
ifc_definition_id=representation.id(),
disable_opening_subtractions=True,
)
IfcStore.edited_objs.add(obj)
bm = bmesh.from_edit_mesh(obj.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
bmesh.update_edit_mesh(obj.data)
bm.free()
def add_object(self, context):
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=self.size)
@@ -1,5 +1,5 @@
import bpy
from blenderbim.bim.ifc import IfcStore
class OpenPieClass(bpy.types.Operator):
bl_idname = "bim.open_pie_class"
@@ -1,12 +1,13 @@
import bpy
import mathutils
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.util.element
import ifcopenshell.util.representation
from . import wall, slab, column
from . import wall, slab, profile
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.pset.data import Data as PsetData
from mathutils import Vector
from mathutils import Vector, Matrix
class AddTypeInstance(bpy.types.Operator):
@@ -22,21 +23,22 @@ class AddTypeInstance(bpy.types.Operator):
def _execute(self, context):
tprops = context.scene.BIMTypeProperties
ifc_class = self.ifc_class or tprops.ifc_class
relating_type = self.relating_type or tprops.relating_type
if not ifc_class or not relating_type:
relating_type_id = self.relating_type or tprops.relating_type
if not ifc_class or not relating_type_id:
return {"FINISHED"}
self.file = IfcStore.get_file()
instance_class = ifcopenshell.util.type.get_applicable_entities(ifc_class, self.file.schema)[0]
if ifc_class == "IfcWallType":
obj = wall.DumbWallGenerator(self.file.by_id(int(relating_type))).generate()
relating_type = self.file.by_id(int(relating_type_id))
material = ifcopenshell.util.element.get_material(relating_type)
if material.is_a("IfcMaterialProfileSet"):
obj = profile.DumbProfileGenerator(relating_type).generate()
if obj:
return {"FINISHED"}
elif ifc_class == "IfcSlabType":
obj = slab.DumbSlabGenerator(self.file.by_id(int(relating_type))).generate()
if obj:
return {"FINISHED"}
elif ifc_class == "IfcColumnType":
obj = column.DumbColumnGenerator(self.file.by_id(int(relating_type))).generate()
elif material.is_a("IfcMaterialLayerSet"):
if ifc_class in ["IfcSlabType", "IfcRoofType", "IfcRampType", "IfcPlateType"]:
obj = slab.DumbSlabGenerator(relating_type).generate()
else:
obj = wall.DumbWallGenerator(relating_type).generate()
if obj:
return {"FINISHED"}
# A cube
@@ -63,7 +65,7 @@ class AddTypeInstance(bpy.types.Operator):
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Instance", mesh)
obj.location = context.scene.cursor.location
collection = bpy.context.view_layer.active_layer_collection.collection
collection = context.view_layer.active_layer_collection.collection
collection.objects.link(obj)
collection_obj = bpy.data.objects.get(collection.name)
bpy.ops.bim.assign_class(obj=obj.name, ifc_class=instance_class)
@@ -73,6 +75,83 @@ class AddTypeInstance(bpy.types.Operator):
return {"FINISHED"}
class AlignProduct(bpy.types.Operator):
bl_idname = "bim.align_product"
bl_label = "Align Product"
bl_options = {"REGISTER", "UNDO"}
align_type: bpy.props.StringProperty()
def execute(self, context):
selected_objs = context.selected_objects
if len(selected_objs) < 2 or not context.active_object:
return {"FINISHED"}
if self.align_type == "CENTERLINE":
point = context.active_object.matrix_world @ (
Vector(context.active_object.bound_box[0]) + (context.active_object.dimensions / 2)
)
elif self.align_type == "POSITIVE":
point = context.active_object.matrix_world @ Vector(context.active_object.bound_box[6])
elif self.align_type == "NEGATIVE":
point = context.active_object.matrix_world @ Vector(context.active_object.bound_box[0])
active_x_axis = context.active_object.matrix_world.to_quaternion() @ Vector((1, 0, 0))
active_y_axis = context.active_object.matrix_world.to_quaternion() @ Vector((0, 1, 0))
active_z_axis = context.active_object.matrix_world.to_quaternion() @ Vector((0, 0, 1))
x_distances = self.get_axis_distances(point, active_x_axis, context)
y_distances = self.get_axis_distances(point, active_y_axis, context)
if abs(sum(x_distances)) < abs(sum(y_distances)):
for i, obj in enumerate(selected_objs):
obj.matrix_world = Matrix.Translation(active_x_axis * -x_distances[i]) @ obj.matrix_world
else:
for i, obj in enumerate(selected_objs):
obj.matrix_world = Matrix.Translation(active_y_axis * -y_distances[i]) @ obj.matrix_world
return {"FINISHED"}
def get_axis_distances(self, point, axis, context):
results = []
for obj in context.selected_objects:
if self.align_type == "CENTERLINE":
obj_point = obj.matrix_world @ (Vector(obj.bound_box[0]) + (obj.dimensions / 2))
elif self.align_type == "POSITIVE":
obj_point = obj.matrix_world @ Vector(obj.bound_box[6])
elif self.align_type == "NEGATIVE":
obj_point = obj.matrix_world @ Vector(obj.bound_box[0])
results.append(mathutils.geometry.distance_point_to_plane(obj_point, point, axis))
return results
class DynamicallyVoidProduct(bpy.types.Operator):
bl_idname = "bim.dynamically_void_product"
bl_label = "Dynamically Void Product"
bl_options = {"REGISTER", "UNDO"}
obj: bpy.props.StringProperty()
def execute(self, context):
obj = bpy.data.objects.get(self.obj)
product = IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id)
if not product.HasOpenings:
return {"FINISHED"}
if [m for m in obj.modifiers if m.type == "BOOLEAN"]:
return {"FINISHED"}
representation = ifcopenshell.util.representation.get_representation(product, "Model", "Body", "MODEL_VIEW")
if not representation:
return {"FINISHED"}
was_edit_mode = obj.mode == "EDIT"
if was_edit_mode:
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.bim.switch_representation(
obj=obj.name,
should_switch_all_meshes=True,
should_reload=True,
ifc_definition_id=representation.id(),
disable_opening_subtractions=True,
)
if was_edit_mode:
bpy.ops.object.mode_set(mode="EDIT")
return {"FINISHED"}
def generate_box(usecase_path, ifc_file, settings):
box_context = ifcopenshell.util.representation.get_context(ifc_file, "Model", "Box", "MODEL_VIEW")
if not box_context:
@@ -98,6 +177,7 @@ def generate_box(usecase_path, ifc_file, settings):
**{"product": product, "representation": new_box}
)
def regenerate_profile_usage(usecase_path, ifc_file, settings):
elements = []
if ifc_file.schema == "IFC2X3":
@@ -117,4 +197,6 @@ def regenerate_profile_usage(usecase_path, ifc_file, settings):
continue
representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW")
if representation:
bpy.ops.bim.switch_representation(obj=obj.name, ifc_definition_id=representation.id(), should_reload=True)
bpy.ops.bim.switch_representation(
obj=obj.name, ifc_definition_id=representation.id(), should_reload=True, should_switch_all_meshes=True
)
@@ -0,0 +1,359 @@
import bpy
import bmesh
import math
import ifcopenshell
import ifcopenshell.util.type
import ifcopenshell.util.unit
import ifcopenshell.util.element
import mathutils.geometry
import blenderbim.bim.handler
from blenderbim.bim.ifc import IfcStore
from math import pi, degrees, inf
from mathutils import Vector, Matrix
from ifcopenshell.api.pset.data import Data as PsetData
from ifcopenshell.api.material.data import Data as MaterialData
from blenderbim.bim.module.geometry.helper import Helper
def element_listener(element, obj):
blenderbim.bim.handler.subscribe_to(obj, "mode", mode_callback)
def mode_callback(obj, data):
for obj in set(bpy.context.selected_objects + [bpy.context.active_object]):
if (
not obj.data
or not isinstance(obj.data, (bpy.types.Mesh, bpy.types.Curve, bpy.types.TextCurve))
or not obj.BIMObjectProperties.ifc_definition_id
or not bpy.context.scene.BIMProjectProperties.is_authoring
):
return
product = IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbProfile":
return
if obj.mode == "EDIT":
IfcStore.edited_objs.add(obj)
bm = bmesh.from_edit_mesh(obj.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
bmesh.update_edit_mesh(obj.data)
bm.free()
else:
material_usage = ifcopenshell.util.element.get_material(product)
x, y = obj.dimensions[0:2]
if not material_usage.CardinalPoint:
new_origin = obj.matrix_world @ (Vector(obj.bound_box[0]) + (Vector((x, y, 0)) / 2))
elif material_usage.CardinalPoint == 1:
new_origin = obj.matrix_world @ Vector(obj.bound_box[4])
elif material_usage.CardinalPoint == 2:
new_origin = obj.matrix_world @ (Vector(obj.bound_box[0]) + (Vector((x, 0, 0)) / 2))
elif material_usage.CardinalPoint == 3:
new_origin = obj.matrix_world @ Vector(obj.bound_box[0])
elif material_usage.CardinalPoint == 4:
new_origin = obj.matrix_world @ (Vector(obj.bound_box[4]) + (Vector((0, y, 0)) / 2))
elif material_usage.CardinalPoint == 5:
new_origin = obj.matrix_world @ (Vector(obj.bound_box[0]) + (Vector((x, y, 0)) / 2))
elif material_usage.CardinalPoint == 6:
new_origin = obj.matrix_world @ (Vector(obj.bound_box[0]) + (Vector((0, y, 0)) / 2))
elif material_usage.CardinalPoint == 7:
new_origin = obj.matrix_world @ Vector(obj.bound_box[7])
elif material_usage.CardinalPoint == 8:
new_origin = obj.matrix_world @ (Vector(obj.bound_box[3]) + (Vector((x, 0, 0)) / 2))
elif material_usage.CardinalPoint == 9:
new_origin = obj.matrix_world @ Vector(obj.bound_box[3])
if (obj.matrix_world.translation - new_origin).length < 0.001:
return
obj.data.transform(
Matrix.Translation(
(obj.matrix_world.inverted().to_quaternion() @ (obj.matrix_world.translation - new_origin))
)
)
obj.matrix_world.translation = new_origin
def ensure_solid(usecase_path, ifc_file, settings):
product = ifc_file.by_id(settings["blender_object"].BIMObjectProperties.ifc_definition_id)
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbProfile":
return
material = ifcopenshell.util.element.get_material(product)
if material and material.is_a("IfcMaterialProfileSetUsage"):
settings["profile_set_usage"] = material
else:
return
settings["ifc_representation_class"] = "IfcExtrudedAreaSolid/IfcMaterialProfileSetUsage"
class DumbProfileGenerator:
def __init__(self, relating_type):
self.relating_type = relating_type
def generate(self):
self.file = IfcStore.get_file()
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(IfcStore.get_file())
material = ifcopenshell.util.element.get_material(self.relating_type)
if material and material.is_a("IfcMaterialProfileSet"):
self.profile_set = material
else:
return
self.collection = bpy.context.view_layer.active_layer_collection.collection
self.collection_obj = bpy.data.objects.get(self.collection.name)
self.length = 3
self.rotation = 0
self.location = Vector((0, 0, 0))
return self.derive_from_cursor()
def derive_from_cursor(self):
self.location = bpy.context.scene.cursor.location
return self.create_profile()
def create_profile(self):
# A cube
verts = [
Vector((-1, -1, -1)),
Vector((-1, -1, 1)),
Vector((-1, 1, -1)),
Vector((-1, 1, 1)),
Vector((1, -1, -1)),
Vector((1, -1, 1)),
Vector((1, 1, -1)),
Vector((1, 1, 1)),
]
edges = []
faces = [
[0, 2, 3, 1],
[2, 3, 7, 6],
[4, 5, 7, 6],
[0, 1, 5, 4],
[1, 3, 7, 5],
[0, 2, 6, 4],
]
mesh = bpy.data.meshes.new(name="Dumb Profile")
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Profile", mesh)
obj.location = self.location
if self.collection_obj and self.collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = self.collection_obj.location[2]
self.collection.objects.link(obj)
ifc_classes = ifcopenshell.util.type.get_applicable_entities(self.relating_type.is_a(), self.file.schema)
# Standard cases are deprecated, so let's cull them
ifc_class = [c for c in ifc_classes if "StandardCase" not in c][0]
obj.name = ifc_class[3:]
bpy.ops.bim.assign_class(obj=obj.name, ifc_class=ifc_class, should_add_representation=False)
if self.relating_type.is_a() in ["IfcBeamType", "IfcMemberType"]:
obj.rotation_euler[0] = math.pi / 2
obj.rotation_euler[2] = math.pi / 2
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
bpy.ops.bim.assign_type(relating_type=self.relating_type.id(), related_object=obj.name)
profile_set_usage = ifcopenshell.util.element.get_material(element)
bpy.ops.bim.add_representation(
obj=obj.name,
context_id=ifcopenshell.util.representation.get_context(self.file, "Model", "Body", "MODEL_VIEW").id(),
ifc_representation_class="IfcExtrudedAreaSolid/IfcMaterialProfileSetUsage",
profile_set_usage=profile_set_usage.id(),
)
representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW")
bpy.ops.bim.switch_representation(
obj=obj.name, ifc_definition_id=representation.id(), should_reload=True, should_switch_all_meshes=True
)
pset = ifcopenshell.api.run("pset.add_pset", self.file, product=element, name="EPset_Parametric")
ifcopenshell.api.run("pset.edit_pset", self.file, pset=pset, properties={"Engine": "BlenderBIM.DumbProfile"})
MaterialData.load(self.file)
obj.select_set(True)
return obj
class DumbProfileRegenerator:
def regenerate_from_profile(self, usecase_path, ifc_file, settings):
self.file = ifc_file
profile = settings["profile"].Profile
if not profile:
return
for element in self.get_elements_using_profile(profile):
self.change_profile(element)
def sync_object_from_profile(self, usecase_path, ifc_file, settings):
self.file = ifc_file
profile = settings["profile"].Profile
if not profile:
return
for element in self.get_elements_using_profile(profile):
self.sync_object(element)
def get_elements_using_profile(self, profile):
results = []
for profile_set in [
mp.ToMaterialProfileSet[0] for mp in self.file.get_inverse(profile) if mp.is_a("IfcMaterialProfile")
]:
for inverse in self.file.get_inverse(profile_set):
if not inverse.is_a("IfcMaterialProfileSetUsage"):
continue
if self.file.schema == "IFC2X3":
for rel in self.file.get_inverse(inverse):
if not rel.is_a("IfcRelAssociatesMaterial"):
continue
results.extend(rel.RelatedObjects)
else:
for rel in inverse.AssociatedTo:
results.extend(rel.RelatedObjects)
return results
def regenerate_from_type(self, usecase_path, ifc_file, settings):
new_material = ifcopenshell.util.element.get_material(settings["relating_type"])
if not new_material or not new_material.is_a("IfcMaterialProfileSet"):
return
self.change_profile(settings["related_object"])
def change_profile(self, element):
obj = IfcStore.get_element(element.id())
if not obj:
return
representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW")
if representation:
bpy.ops.bim.switch_representation(
obj=obj.name, ifc_definition_id=representation.id(), should_reload=True, should_switch_all_meshes=True
)
def sync_object(self, element):
obj = IfcStore.get_element(element.id())
if not obj or obj not in IfcStore.edited_objs:
return
bpy.ops.bim.update_representation(obj=obj.name)
class ExtendProfile(bpy.types.Operator):
bl_idname = "bim.extend_profile"
bl_label = "Extend Profile"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
selected_objs = context.selected_objects
for obj in selected_objs:
bpy.ops.bim.dynamically_void_product(obj=obj.name)
if len(selected_objs) == 0:
return {"FINISHED"}
if not context.active_object:
return {"FINISHED"}
if len(selected_objs) == 1:
DumbProfileExtender(context.active_object, target_coordinate=context.scene.cursor.location).extend()
IfcStore.edited_objs.add(context.active_object)
return {"FINISHED"}
if len(selected_objs) < 2:
return {"FINISHED"}
for obj in selected_objs:
if obj == context.active_object:
continue
DumbProfileExtender(obj, context.active_object).extend()
IfcStore.edited_objs.add(obj)
return {"FINISHED"}
class DumbProfileExtender:
# A profile is a prismatic extrusion along its local Z axis.
def __init__(self, profile, target=None, target_coordinate=None):
self.profile = profile
self.target = target
self.target_coordinate = target_coordinate
# An extension of a profile is determined by casting a ray from the cardinal
# point of either extreme along the profiles local Z axis to a target
# object. The nearest result from this raycast will be the target extension
# point.
def extend(self):
extension_data = self.get_closest_extension_point()
if not extension_data:
return
if extension_data["end"] == "bottom":
self.profile.matrix_world.translation = extension_data["contact"]
if extension_data["direction"] == "up":
self.shift_top_faces(-extension_data["distance"])
elif extension_data["direction"] == "down":
self.shift_top_faces(extension_data["distance"])
if extension_data["end"] == "top":
if extension_data["direction"] == "up":
self.shift_top_faces(extension_data["distance"])
elif extension_data["direction"] == "down":
self.shift_top_faces(-extension_data["distance"])
def shift_top_faces(self, z):
vertices = []
for f in self.get_profile_top_faces():
vertices.extend(f.vertices)
for v in set(vertices):
self.profile.data.vertices[v].co.z += z
# An top face is defined as having at least one vertex on the max
# Z-axis, and a non-insignificant Z component of its face normal
def get_profile_top_faces(self):
faces = []
max_z = max([v[2] for v in self.profile.bound_box])
for f in self.profile.data.polygons:
if abs(f.normal.z) < 0.1:
continue
for v in f.vertices:
if self.profile.data.vertices[v].co.z == max_z:
faces.append(f)
break
return faces
def get_closest_extension_point(self):
top = self.profile.matrix_world @ Vector((0, 0, self.profile.dimensions[2]))
bottom = self.profile.matrix_world.translation
up = self.profile.matrix_world.to_quaternion() @ Vector((0, 0, 1))
down = self.profile.matrix_world.to_quaternion() @ Vector((0, 0, -1))
if self.target:
return self.get_closest_extension_point_from_target_obj(top, bottom, up, down)
elif self.target_coordinate:
return self.get_closest_extension_point_from_target_coordinate(top, bottom, up, down)
def get_closest_extension_point_from_target_coordinate(self, top, bottom, up, down):
point = mathutils.geometry.intersect_line_plane(
bottom, top, self.target_coordinate, self.profile.matrix_world.to_quaternion() @ Vector((0, 0, 1))
)
if not point:
return
top_distance = (point - top).length
bottom_distance = (point - bottom).length
if top_distance < bottom_distance:
intersection_point, signed_distance = mathutils.geometry.intersect_point_line(point, top, bottom)
if signed_distance > 0:
return {"contact": point, "distance": top_distance, "end": "top", "direction": "down"}
else:
return {"contact": point, "distance": top_distance, "end": "top", "direction": "up"}
else:
intersection_point, signed_distance = mathutils.geometry.intersect_point_line(point, bottom, top)
if signed_distance > 0:
return {"contact": point, "distance": bottom_distance, "end": "bottom", "direction": "up"}
else:
return {"contact": point, "distance": bottom_distance, "end": "bottom", "direction": "down"}
def get_closest_extension_point_from_target_obj(self, top, bottom, up, down):
t_top = self.target.matrix_world.inverted() @ top
t_bottom = self.target.matrix_world.inverted() @ bottom
t_up = self.target.matrix_world.inverted().to_quaternion() @ up
t_down = self.target.matrix_world.inverted().to_quaternion() @ down
results = []
results.append((self.target.ray_cast(t_top, t_up, distance=50), top, "top", "up"))
results.append((self.target.ray_cast(t_top, t_down, distance=50), top, "top", "down"))
results.append((self.target.ray_cast(t_bottom, t_up, distance=50), bottom, "bottom", "up"))
results.append((self.target.ray_cast(t_bottom, t_down, distance=50), bottom, "bottom", "down"))
min_distance = float(inf)
final = None
for result in results:
if result[0][0]:
contact = self.target.matrix_world @ result[0][1]
distance = (contact - result[1]).length
if distance < min_distance:
min_distance = distance
final = {"contact": contact, "distance": distance, "end": result[2], "direction": result[3]}
return final
@@ -0,0 +1,22 @@
import bpy
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.style.data import Data as StyleData
def sync_name(usecase_path, ifc_file, settings):
if "Name" not in settings["attributes"]:
return
obj = IfcStore.get_element(settings["product"].id())
if not obj:
return
if isinstance(obj, bpy.types.Object):
new_name = "{}/{}".format(settings["product"].is_a(), settings["attributes"]["Name"] or "Unnamed")
elif isinstance(obj, bpy.types.Material):
new_name = settings["attributes"]["Name"] or "Unnamed"
if obj.BIMMaterialProperties.ifc_style_id:
IfcStore.get_file().by_id(obj.BIMMaterialProperties.ifc_style_id).Name = new_name
StyleData.load(IfcStore.get_file(), obj.BIMMaterialProperties.ifc_style_id)
collection = bpy.data.collections.get(obj.name)
if collection:
collection.name = new_name
obj.name = new_name
@@ -195,6 +195,42 @@ def calculate_quantities(usecase_path, ifc_file, settings):
PsetData.load(ifc_file, obj.BIMObjectProperties.ifc_definition_id)
class AddSlabOpening(bpy.types.Operator):
bl_idname = "bim.add_slab_opening"
bl_label = "Add Slab Opening"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
selected_objs = context.selected_objects
if len(selected_objs) == 0 or not context.active_object:
return {"FINISHED"}
slab_obj = context.active_object
if not slab_obj.BIMObjectProperties.ifc_definition_id:
return {"FINISHED"}
slab = IfcStore.get_file().by_id(slab_obj.BIMObjectProperties.ifc_definition_id)
local_location = slab_obj.matrix_world.inverted() @ context.scene.cursor.location
raycast = slab_obj.closest_point_on_mesh(local_location, distance=0.01)
if not raycast[0]:
return {"FINISHED"}
bpy.ops.mesh.primitive_cube_add(size=slab_obj.dimensions[2] * 2)
opening = context.selected_objects[0]
# Place the opening in the middle of the slab
global_location = slab_obj.matrix_world @ raycast[1]
normal = raycast[2]
normal.negate()
global_normal = slab_obj.matrix_world.to_quaternion() @ normal
opening.location = global_location + (global_normal * (slab_obj.dimensions[2] / 2))
opening.rotation_euler = slab_obj.rotation_euler
opening.name = "Opening"
bpy.ops.bim.add_opening(opening=opening.name, obj=slab_obj.name)
return {"FINISHED"}
class DumbSlabGenerator:
def __init__(self, relating_type):
self.relating_type = relating_type
@@ -242,7 +278,12 @@ class DumbSlabGenerator:
modifier.use_even_offset = True
modifier.offset = 1
modifier.thickness = self.depth
obj.name = "Slab"
ifc_classes = ifcopenshell.util.type.get_applicable_entities(self.relating_type.is_a(), self.file.schema)
# Standard cases are deprecated, so let's cull them
ifc_class = [c for c in ifc_classes if "StandardCase" not in c][0]
obj.name = ifc_class[3:]
obj.location = self.location
if self.collection_obj and self.collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = self.collection_obj.location[2] - self.depth
@@ -251,8 +292,7 @@ class DumbSlabGenerator:
self.collection.objects.link(obj)
bpy.ops.bim.assign_class(
obj=obj.name,
ifc_class="IfcSlab",
predefined_type="FLOOR",
ifc_class=ifc_class,
ifc_representation_class="IfcExtrudedAreaSolid/IfcArbitraryProfileDefWithVoids",
)
bpy.ops.bim.assign_type(relating_type=self.relating_type.id(), related_object=obj.name)
@@ -9,6 +9,10 @@ class BIM_PT_authoring(Panel):
bl_region_type = "UI"
bl_category = "BlenderBIM"
@classmethod
def poll(cls, context):
return IfcStore.get_file()
def draw(self, context):
tprops = context.scene.BIMTypeProperties
col = self.layout.column(align=True)
@@ -20,7 +20,7 @@ def element_listener(element, obj):
def mode_callback(obj, data):
for obj in bpy.context.selected_objects + [bpy.context.active_object]:
for obj in set(bpy.context.selected_objects + [bpy.context.active_object]):
if (
obj.mode != "EDIT"
or not obj.data
@@ -33,21 +33,47 @@ def mode_callback(obj, data):
parametric = ifcopenshell.util.element.get_psets(product).get("EPset_Parametric")
if not parametric or parametric["Engine"] != "BlenderBIM.DumbWall":
return
bpy.ops.bim.dynamically_void_product(obj=obj.name)
IfcStore.edited_objs.add(obj)
bm = bmesh.from_edit_mesh(obj.data)
bmesh.ops.dissolve_limit(bm, angle_limit=pi / 180 * 1, verts=bm.verts, edges=bm.edges)
bmesh.update_edit_mesh(obj.data)
bm.free()
class AddWall(bpy.types.Operator):
bl_idname = "bim.add_wall"
bl_label = "Add Wall"
class AddWallOpening(bpy.types.Operator):
bl_idname = "bim.add_wall_opening"
bl_label = "Add Wall Opening"
bl_options = {"REGISTER", "UNDO"}
join_type: bpy.props.StringProperty()
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
props = context.scene.BIMModelProperties
bpy.ops.bim.add_type_instance(ifc_class="IfcWallType", relating_type=int(props.relating_type))
selected_objs = context.selected_objects
if len(selected_objs) == 0 or not context.active_object:
return {"FINISHED"}
wall_obj = context.active_object
if not wall_obj.BIMObjectProperties.ifc_definition_id:
return {"FINISHED"}
wall = IfcStore.get_file().by_id(wall_obj.BIMObjectProperties.ifc_definition_id)
local_location = wall_obj.matrix_world.inverted() @ context.scene.cursor.location
raycast = wall_obj.closest_point_on_mesh(local_location, distance=0.01)
if not raycast[0]:
return {"FINISHED"}
bpy.ops.mesh.primitive_cube_add(size=wall_obj.dimensions[1] * 2)
opening = bpy.context.selected_objects[0]
# Place the opening in the middle of the wall
global_location = wall_obj.matrix_world @ raycast[1]
normal = raycast[2]
normal.negate()
global_normal = wall_obj.matrix_world.to_quaternion() @ normal
opening.location = global_location + (global_normal * (wall_obj.dimensions[1] / 2))
opening.rotation_euler = wall_obj.rotation_euler
opening.name = "Opening"
bpy.ops.bim.add_opening(opening=opening.name, obj=wall_obj.name)
return {"FINISHED"}
@@ -59,13 +85,21 @@ class JoinWall(bpy.types.Operator):
def execute(self, context):
selected_objs = context.selected_objects
for obj in selected_objs:
bpy.ops.bim.dynamically_void_product(obj=obj.name)
if len(selected_objs) == 0:
return {"FINISHED"}
if not self.join_type:
for obj in selected_objs:
DumbWallJoiner(obj, obj).unjoin()
return {"FINISHED"}
if len(selected_objs) < 2 or not context.active_object:
if not context.active_object:
return {"FINISHED"}
if len(selected_objs) == 1:
DumbWallJoiner(context.active_object, target_coordinate=context.scene.cursor.location).extend()
IfcStore.edited_objs.add(context.active_object)
return {"FINISHED"}
if len(selected_objs) < 2:
return {"FINISHED"}
for obj in selected_objs:
if obj == context.active_object:
@@ -148,6 +182,8 @@ def recalculate_dumb_wall_origin(wall, new_origin=None):
)
)
wall.matrix_world.translation = new_origin
for child in wall.children:
child.matrix_parent_inverse = wall.matrix_world.inverted()
class DumbWallSplitter:
@@ -223,6 +259,9 @@ class DumbWallFlipper:
).length < 0.001:
recalculate_dumb_wall_origin(self.wall, self.wall.matrix_world @ Vector(self.wall.bound_box[7]))
self.rotate_wall_180()
bpy.context.view_layer.update()
for child in self.wall.children:
child.matrix_parent_inverse = self.wall.matrix_world.inverted()
else:
recalculate_dumb_wall_origin(self.wall)
@@ -327,16 +366,19 @@ class DumbWallJoiner:
# 2. Given an "end face", identify a side "target face" of the other wall
# to project towards.
# 3. Project the vertices of an "end face" to the "target face".
def __init__(self, wall1, wall2):
# Alternatively, a target coordinate may be provided as an imaginary point for the wall to join to
def __init__(self, wall1, wall2=None, target_coordinate=None):
self.wall1 = wall1
self.wall2 = wall2
self.target_coordinate = target_coordinate
self.should_project_to_frontface = True
self.should_attempt_v_junction_projection = False
self.initialise_convenience_variables()
def initialise_convenience_variables(self):
self.wall1_matrix = self.wall1.matrix_world
self.wall2_matrix = self.wall2.matrix_world
if self.wall2:
self.wall2_matrix = self.wall2.matrix_world
self.pos_x = self.wall1_matrix.to_quaternion() @ Vector((1, 0, 0))
self.neg_x = self.wall1_matrix.to_quaternion() @ Vector((-1, 0, 0))
@@ -354,6 +396,26 @@ class DumbWallJoiner:
self.wall1.data.vertices[v].co[0] = max_x
self.recalculate_origins()
# An extension is where a single end of wall1 is projected to an imaginary
# plane denoted by the target coordinate.
def extend(self):
wall1_min_faces, wall1_max_faces = self.get_wall_end_faces(self.wall1)
ef1_distance = abs(mathutils.geometry.distance_point_to_plane(
self.wall1_matrix @ self.wall1.data.vertices[wall1_min_faces[0].vertices[0]].co,
self.target_coordinate,
self.pos_x,
))
ef2_distance = abs(mathutils.geometry.distance_point_to_plane(
self.wall1_matrix @ self.wall1.data.vertices[wall1_max_faces[0].vertices[0]].co,
self.target_coordinate,
self.neg_x,
))
if ef1_distance < ef2_distance:
self.project_end_faces_to_target(wall1_min_faces)
else:
self.project_end_faces_to_target(wall1_max_faces)
self.recalculate_origins()
# A T-junction is an ordered operation where a single end of wall1 is joined
# to wall2 if possible (i.e. walls aren't parallel). Wall2 is not modified.
# First, wall1 end faces are identified. We attempt to project an end face
@@ -439,7 +501,8 @@ class DumbWallJoiner:
def recalculate_origins(self):
bpy.context.view_layer.update()
recalculate_dumb_wall_origin(self.wall1)
recalculate_dumb_wall_origin(self.wall2)
if self.wall2:
recalculate_dumb_wall_origin(self.wall2)
def swap_walls(self):
self.wall1, self.wall2 = self.wall2, self.wall1
@@ -467,6 +530,14 @@ class DumbWallJoiner:
local_point = wall_matrix.inverted() @ point
wall.data.vertices[v].co = local_point
def project_end_faces_to_target(self, end_faces):
for end_face in end_faces:
for v in end_face.vertices:
vertex = self.wall1_matrix @ self.wall1.data.vertices[v].co
self.wall1.data.vertices[v].co = self.wall1_matrix.inverted() @ mathutils.geometry.intersect_line_plane(
vertex, vertex + self.pos_x, self.target_coordinate, self.pos_x
)
# A projection target face is a side face on the target wall that has a
# significant local Y component to its normal (i.e. is not pointing up or
# down or something). In addition, its plane must intersect with the
@@ -536,6 +607,8 @@ class DumbWallJoiner:
min_x = min([v[0] for v in wall.bound_box])
max_x = max([v[0] for v in wall.bound_box])
for f in wall.data.polygons:
if abs(f.normal.x) < 0.1:
continue
end_face_index = self.get_wall_face_end(wall, f, min_x, max_x)
if end_face_index == 1:
min_faces.append(f)
@@ -546,9 +619,9 @@ class DumbWallJoiner:
# 1 is the leftmost (minimum local X axis) end, and 2 is the rightmost end
def get_wall_face_end(self, wall, face, min_x, max_x):
for v in face.vertices:
if wall.data.vertices[v].co.x == min_x and abs(face.normal.x) > 0.1:
if wall.data.vertices[v].co.x == min_x:
return 1
if wall.data.vertices[v].co.x == max_x and abs(face.normal.x) > 0.1:
if wall.data.vertices[v].co.x == max_x:
return 2
@@ -698,17 +771,24 @@ class DumbWallGenerator:
]
mesh = bpy.data.meshes.new(name="Wall")
mesh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new("Wall", mesh)
ifc_classes = ifcopenshell.util.type.get_applicable_entities(self.relating_type.is_a(), self.file.schema)
# Standard cases are deprecated, so let's cull them
ifc_class = [c for c in ifc_classes if "StandardCase" not in c][0]
obj = bpy.data.objects.new(ifc_class[3:], mesh)
obj.location = self.location
obj.rotation_euler[2] = self.rotation
if self.collection_obj and self.collection_obj.BIMObjectProperties.ifc_definition_id:
obj.location[2] = self.collection_obj.location[2]
self.collection.objects.link(obj)
bpy.ops.bim.assign_class(
obj=obj.name,
ifc_class="IfcWall",
ifc_class=ifc_class,
ifc_representation_class="IfcExtrudedAreaSolid/IfcArbitraryClosedProfileDef",
)
bpy.ops.bim.assign_type(relating_type=self.relating_type.id(), related_object=obj.name)
element = self.file.by_id(obj.BIMObjectProperties.ifc_definition_id)
pset = ifcopenshell.api.run("pset.add_pset", self.file, product=element, name="EPset_Parametric")
@@ -67,7 +67,7 @@ def add_object(self, context):
obj = bpy.data.objects.new("Window Profile", mesh)
context.view_layer.active_layer_collection.collection.objects.link(obj)
bpy.context.view_layer.objects.active = obj
context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.convert(target="CURVE")
@@ -85,7 +85,7 @@ def add_object(self, context):
obj2 = bpy.data.objects.new("Window", mesh)
context.view_layer.active_layer_collection.collection.objects.link(obj2)
bpy.context.view_layer.objects.active = obj2
context.view_layer.objects.active = obj2
obj2.select_set(True)
bpy.ops.object.convert(target="CURVE")
obj2.data.splines[0].use_cyclic_u = True
@@ -116,11 +116,11 @@ def add_object(self, context):
modifier.thickness = self.overall_height - 0.08
context.view_layer.active_layer_collection.collection.objects.link(obj3)
bpy.context.view_layer.objects.active = obj3
context.view_layer.objects.active = obj3
obj3.select_set(True)
bpy.ops.object.convert(target="MESH")
ctx = bpy.context.copy()
ctx = context.copy()
ctx["active_object"] = obj2
ctx["selected_editable_objects"] = [obj2, obj3]
bpy.ops.object.join(ctx)
@@ -142,7 +142,7 @@ def add_object(self, context):
modifier.thickness = self.overall_height
context.view_layer.active_layer_collection.collection.objects.link(obj4)
bpy.context.view_layer.objects.active = obj4
context.view_layer.objects.active = obj4
obj4.select_set(True)
bpy.ops.object.convert(target="MESH")
obj4.display_type = "WIRE"
@@ -1,6 +1,7 @@
import os
import bpy
from bpy.types import WorkSpaceTool
from blenderbim.bim.ifc import IfcStore
class BimTool(WorkSpaceTool):
@@ -16,44 +17,138 @@ class BimTool(WorkSpaceTool):
bl_keymap = (
# ("bim.wall_tool_op", {"type": 'MOUSEMOVE', "value": 'ANY'}, {"properties": []}),
# ("mesh.add_wall", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": []}),
("bim.add_wall", {"type": "A", "value": "PRESS", "shift": True}, {"properties": []}),
("bim.join_wall", {"type": "E", "value": "PRESS", "shift": True}, {"properties": [("join_type", "T")]}),
("bim.add_type_instance", {"type": "A", "value": "PRESS", "shift": True}, {"properties": []}),
("bim.hotkey", {"type": "E", "value": "PRESS", "shift": True}, {"properties": [("hotkey", "S_E")]}),
("bim.join_wall", {"type": "T", "value": "PRESS", "shift": True}, {"properties": [("join_type", "L")]}),
("bim.join_wall", {"type": "Y", "value": "PRESS", "shift": True}, {"properties": [("join_type", "V")]}),
("bim.flip_wall", {"type": "F", "value": "PRESS", "shift": True}, {"properties": []}),
("bim.split_wall", {"type": "S", "value": "PRESS", "shift": True}, {"properties": []}),
(
"bim.align_wall",
{"type": "X", "value": "PRESS", "shift": True},
{"properties": [("align_type", "EXTERIOR")]},
),
(
"bim.align_wall",
{"type": "C", "value": "PRESS", "shift": True},
{"properties": [("align_type", "CENTERLINE")]},
),
(
"bim.align_wall",
{"type": "V", "value": "PRESS", "shift": True},
{"properties": [("align_type", "INTERIOR")]},
),
("bim.hotkey", {"type": "X", "value": "PRESS", "shift": True}, {"properties": [("hotkey", "S_X")]}),
("bim.hotkey", {"type": "C", "value": "PRESS", "shift": True}, {"properties": [("hotkey", "S_C")]}),
("bim.hotkey", {"type": "V", "value": "PRESS", "shift": True}, {"properties": [("hotkey", "S_V")]}),
("bim.hotkey", {"type": "O", "value": "PRESS", "shift": True}, {"properties": [("hotkey", "S_O")]}),
("bim.hotkey", {"type": "O", "value": "PRESS", "alt": True}, {"properties": [("hotkey", "A_O")]}),
("bim.hotkey", {"type": "D", "value": "PRESS", "alt": True}, {"properties": [("hotkey", "A_D")]}),
)
def draw_settings(context, layout, tool):
props = context.scene.BIMModelProperties
row = layout.row(align=True)
props = context.scene.BIMTypeProperties
row.prop(props, "ifc_class", text="")
row.prop(props, "relating_type", text="")
row.label(text="", icon="BLANK1")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Add", icon="EVENT_A")
row.label(text="Extend", icon="EVENT_E")
row.label(text="Butt", icon="EVENT_T")
row.label(text="Mitre", icon="EVENT_Y")
row.label(text="Flip", icon="EVENT_F")
row.label(text="Split", icon="EVENT_S")
row.label(text="", icon="EVENT_X")
row.label(text="", icon="EVENT_C")
row.label(text="", icon="EVENT_V")
row.label(text="Add Type Instance", icon="EVENT_A")
if props.ifc_class == "IfcWallType":
row = layout.row()
row.label(text="Join")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Extend", icon="EVENT_E")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Butt", icon="EVENT_T")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Mitre", icon="EVENT_Y")
row = layout.row()
row.label(text="Wall Tools")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Flip", icon="EVENT_F")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Split", icon="EVENT_S")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Opening", icon="EVENT_O")
if props.ifc_class == "IfcSlabType":
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Opening", icon="EVENT_O")
if props.ifc_class in ["IfcColumnType", "IfcBeamType", "IfcMemberType"]:
row = layout.row()
row.label(text="Join")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Extend", icon="EVENT_E")
row = layout.row(align=True)
row.label(text="Align")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Align Exterior", icon="EVENT_X")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Align Centerline", icon="EVENT_C")
row = layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="Align Interior", icon="EVENT_V")
row = layout.row(align=True)
row = layout.row(align=True)
row.label(text="Mode")
row = layout.row(align=True)
row.label(text="", icon="EVENT_ALT")
row.label(text="Opening", icon="EVENT_O")
row = layout.row(align=True)
row.label(text="", icon="EVENT_ALT")
row.label(text="Decomposition", icon="EVENT_D")
class Hotkey(bpy.types.Operator):
bl_idname = "bim.hotkey"
bl_label = "Hotkey"
bl_options = {"REGISTER", "UNDO"}
hotkey: bpy.props.StringProperty()
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
self.props = context.scene.BIMTypeProperties
getattr(self, f"hotkey_{self.hotkey}")()
return {"FINISHED"}
def hotkey_S_C(self):
if self.props.ifc_class == "IfcWallType":
bpy.ops.bim.align_wall(align_type="CENTERLINE")
else:
bpy.ops.bim.align_product(align_type="CENTERLINE")
def hotkey_S_E(self):
if self.props.ifc_class == "IfcWallType":
bpy.ops.bim.join_wall(join_type="T")
elif self.props.ifc_class in ["IfcColumnType", "IfcBeamType", "IfcMemberType"]:
bpy.ops.bim.extend_profile()
def hotkey_S_V(self):
if self.props.ifc_class == "IfcWallType":
bpy.ops.bim.align_wall(align_type="INTERIOR")
else:
bpy.ops.bim.align_product(align_type="POSITIVE")
def hotkey_S_X(self):
if self.props.ifc_class == "IfcWallType":
bpy.ops.bim.align_wall(align_type="EXTERIOR")
else:
bpy.ops.bim.align_product(align_type="NEGATIVE")
def hotkey_S_O(self):
if self.props.ifc_class == "IfcWallType":
bpy.ops.bim.add_wall_opening()
elif self.props.ifc_class == "IfcSlabType":
bpy.ops.bim.add_slab_opening()
def hotkey_A_D(self):
bpy.ops.bim.toggle_decomposition_parenting()
def hotkey_A_O(self):
bpy.ops.bim.toggle_opening_visibility()
@@ -2,6 +2,7 @@ import bpy
from . import ui, prop, operator
classes = (
operator.AddOrRemoveElementFromCollection,
operator.EnableEditingPerson,
operator.DisableEditingPerson,
operator.AddPerson,
@@ -1,10 +1,49 @@
import bpy
import json
import ifcopenshell.api
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.owner.data import Data
def flatten_collection(collection):
return [v.name for v in collection] if collection else None
def populate_collection(collection, collection_data):
collection.clear()
if collection_data:
for value in collection_data:
collection.add().name = value
else:
collection.add()
class AddOrRemoveElementFromCollection(bpy.types.Operator):
bl_idname = "bim.add_or_remove_element_from_collection"
bl_label = "Add or Remove Element From Collection"
bl_options = {"REGISTER", "UNDO"}
operation : bpy.props.EnumProperty(
items=(
("+", 'Add', "Add item to collection"),
("-", 'Remove', "Remove item from collection")
),
default="+",
)
collection_path : bpy.props.StringProperty()
selected_item_idx : bpy.props.IntProperty(default=-1)
def execute(self, context):
# Ugly but I hate using eval()
collection = context.scene
for attr in self.collection_path.split("."):
if hasattr(collection, attr):
collection = getattr(collection, attr)
if self.operation == "+" and hasattr(collection, "add"):
collection.add()
elif hasattr(collection, "remove") and 0 <= self.selected_item_idx < len(collection):
collection.remove(self.selected_item_idx)
return {"FINISHED"}
class EnableEditingPerson(bpy.types.Operator):
bl_idname = "bim.enable_editing_person"
bl_label = "Enable Editing Person"
@@ -17,12 +56,13 @@ class EnableEditingPerson(bpy.types.Operator):
props.active_person_id = self.person_id
data = Data.people[self.person_id]
name = data["Id"] if self.file.schema == "IFC2X3" else data["Identification"]
props.person.name = name or ""
props.person.family_name = data["FamilyName"] or ""
props.person.given_name = data["GivenName"] or ""
props.person.middle_names = json.dumps(data["MiddleNames"]) if data["MiddleNames"] else ""
props.person.prefix_titles = json.dumps(data["PrefixTitles"]) if data["PrefixTitles"] else ""
props.person.suffix_titles = json.dumps(data["SuffixTitles"]) if data["SuffixTitles"] else ""
person = props.person
person.name = name or ""
person.family_name = data["FamilyName"] or ""
person.given_name = data["GivenName"] or ""
populate_collection(person.middle_names, data.get("MiddleNames", None))
populate_collection(person.prefix_titles, data.get("PrefixTitles", None))
populate_collection(person.suffix_titles, data.get("SuffixTitles", None))
return {"FINISHED"}
@@ -61,13 +101,14 @@ class EditPerson(bpy.types.Operator):
def _execute(self, context):
self.file = IfcStore.get_file()
props = context.scene.BIMOwnerProperties
person = props.person
attributes = {
"Identification": props.person.name or None,
"FamilyName": props.person.family_name or None,
"GivenName": props.person.given_name or None,
"MiddleNames": json.loads(props.person.middle_names) if props.person.middle_names else None,
"PrefixTitles": json.loads(props.person.prefix_titles) if props.person.prefix_titles else None,
"SuffixTitles": json.loads(props.person.suffix_titles) if props.person.suffix_titles else None,
"Identification": person.name or None,
"FamilyName": person.family_name or None,
"GivenName": person.given_name or None,
"MiddleNames": flatten_collection(person.middle_names),
"PrefixTitles": flatten_collection(person.prefix_titles),
"SuffixTitles": flatten_collection(person.suffix_titles),
}
if self.file.schema == "IFC2X3":
attributes["Id"] = attributes["Identification"]
@@ -215,29 +256,28 @@ class EnableEditingAddress(bpy.types.Operator):
props = context.scene.BIMOwnerProperties
props.active_address_id = self.address_id
data = Data.addresses[self.address_id]
props.address.name = data["type"]
props.address.purpose = data["Purpose"] or "None"
props.address.description = data["Description"] or ""
props.address.user_defined_purpose = data["UserDefinedPurpose"] or ""
address = props.address
address.name = data["type"]
address.purpose = data["Purpose"] or "None"
address.description = data["Description"] or ""
address.user_defined_purpose = data["UserDefinedPurpose"] or ""
if data["type"] == "IfcTelecomAddress":
props.address.telephone_numbers = json.dumps(data["TelephoneNumbers"]) if data["TelephoneNumbers"] else ""
props.address.facsimile_numbers = json.dumps(data["FacsimileNumbers"]) if data["FacsimileNumbers"] else ""
props.address.pager_number = data["PagerNumber"] or ""
props.address.electronic_mail_addresses = (
json.dumps(data["ElectronicMailAddresses"]) if data["ElectronicMailAddresses"] else ""
)
props.address.www_home_page_url = data["WWWHomePageURL"] or ""
if data["type"] == "IfcTelecomAddress":
populate_collection(address.telephone_numbers, data.get("TelephoneNumbers", None))
populate_collection(address.facsimile_numbers, data.get("FacsimileNumbers", None))
address.pager_number = data["PagerNumber"] or ""
populate_collection(address.electronic_mail_addresses, data.get("ElectronicMailAddresses", None))
address.www_home_page_url = data["WWWHomePageURL"] or ""
if self.file.schema != "IFC2X3":
props.address.messaging_ids = json.dumps(data["MessagingIDs"]) if data["MessagingIDs"] else ""
populate_collection(address.messaging_ids, data.get("MessagingIDs", None))
elif data["type"] == "IfcPostalAddress":
props.address.internal_location = data["InternalLocation"] or ""
props.address.address_lines = json.dumps(data["AddressLines"]) if data["AddressLines"] else ""
props.address.postal_box = data["PostalBox"] or ""
props.address.town = data["Town"] or ""
props.address.region = data["Region"] or ""
props.address.postal_code = data["PostalCode"] or ""
props.address.country = data["Country"] or ""
address.internal_location = data["InternalLocation"] or ""
populate_collection(address.address_lines, data.get("AddressLines", None))
address.postal_box = data["PostalBox"] or ""
address.town = data["Town"] or ""
address.region = data["Region"] or ""
address.postal_code = data["PostalCode"] or ""
address.country = data["Country"] or ""
return {"FINISHED"}
@@ -273,18 +313,12 @@ class EditAddress(bpy.types.Operator):
if address.is_a("IfcTelecomAddress"):
attributes.update(
{
"TelephoneNumbers": json.loads(props.address.telephone_numbers)
if props.address.telephone_numbers
else None,
"FacsimileNumbers": json.loads(props.address.facsimile_numbers)
if props.address.facsimile_numbers
else None,
"TelephoneNumbers": flatten_collection(props.address.telephone_numbers),
"FacsimileNumbers": flatten_collection(props.address.facsimile_numbers),
"PagerNumber": props.address.pager_number or None,
"ElectronicMailAddresses": json.loads(props.address.electronic_mail_addresses)
if props.address.electronic_mail_addresses
else None,
"ElectronicMailAddresses": flatten_collection(props.address.electronic_mail_addresses),
"WWWHomePageURL": props.address.www_home_page_url or None,
"MessagingIDs": json.loads(props.address.messaging_ids) if props.address.messaging_ids else None,
"MessagingIDs": flatten_collection(props.address.messaging_ids),
}
)
if self.file.schema == "IFC2X3":
@@ -293,7 +327,7 @@ class EditAddress(bpy.types.Operator):
attributes.update(
{
"InternalLocation": props.address.internal_location or None,
"AddressLines": json.loads(props.address.address_lines) if props.address.address_lines else None,
"AddressLines": flatten_collection(props.address.address_lines),
"PostalBox": props.address.postal_box or None,
"Town": props.address.town or None,
"Region": props.address.region or None,
@@ -14,27 +14,37 @@ from bpy.props import (
CollectionProperty,
)
_persons_enum = []
_organisations_enum = []
def purge():
global _persons_enum
global _organisations_enum
_persons_enum.clear()
_organisations_enum.clear()
def getPersons(self, context):
global _persons_enum
if not Data.is_loaded:
Data.load(IfcStore.get_file())
results = []
_persons_enum.clear()
for ifc_id, person in Data.people.items():
if "Id" in person:
identifier = person["Id"] or ""
else:
identifier = person["Identification"] or ""
results.append((str(ifc_id), identifier, ""))
return results
_persons_enum.append((str(ifc_id), identifier, ""))
return _persons_enum
def getOrganisations(self, context):
global _organisations_enum
if not Data.is_loaded:
Data.load(IfcStore.get_file())
results = []
_organisations_enum.clear()
for ifc_id, organisation in Data.organisations.items():
results.append((str(ifc_id), organisation["Name"], ""))
return results
_organisations_enum.append((str(ifc_id), organisation["Name"], ""))
return _organisations_enum
class Address(PropertyGroup):
@@ -54,19 +64,19 @@ class Address(PropertyGroup):
user_defined_purpose: StringProperty(name="Custom Purpose")
internal_location: StringProperty(name="Internal Location")
address_lines: StringProperty(name="Address")
address_lines: CollectionProperty(type=StrProperty, name="Address")
postal_box: StringProperty(name="Postal Box")
town: StringProperty(name="Town")
region: StringProperty(name="Region")
postal_code: StringProperty(name="Postal Code")
country: StringProperty(name="Country")
telephone_numbers: StringProperty(name="Telephone Numbers")
facsimile_numbers: StringProperty(name="Facsimile Numbers")
telephone_numbers: CollectionProperty(type=StrProperty, name="Telephone Numbers")
facsimile_numbers: CollectionProperty(type=StrProperty, name="Facsimile Numbers")
pager_number: StringProperty(name="Pager Number")
electronic_mail_addresses: StringProperty(name="Emails")
www_home_page_url: StringProperty(name="Websites")
messaging_ids: StringProperty(name="IMs")
electronic_mail_addresses: CollectionProperty(type=StrProperty, name="Emails")
www_home_page_url: StringProperty(name="Website")
messaging_ids: CollectionProperty(type=StrProperty, name="IMs")
class Role(PropertyGroup):
@@ -112,9 +122,9 @@ class Person(PropertyGroup):
name: StringProperty(name="Identification")
family_name: StringProperty(name="Family Name")
given_name: StringProperty(name="Given Name")
middle_names: StringProperty(name="Middle Names")
prefix_titles: StringProperty(name="Prefixes")
suffix_titles: StringProperty(name="Suffixes")
middle_names: CollectionProperty(type=StrProperty, name="Middle Names")
prefix_titles: CollectionProperty(type=StrProperty, name="Prefixes")
suffix_titles: CollectionProperty(type=StrProperty, name="Suffixes")
class BIMOwnerProperties(PropertyGroup):
@@ -2,10 +2,39 @@ import bpy
from bpy.types import Panel
from ifcopenshell.api.owner.data import Data
from blenderbim.bim.ifc import IfcStore
from .operator import AddOrRemoveElementFromCollection
def draw_roles_ui(box, assigned_object_id, roles):
props = bpy.context.scene.BIMOwnerProperties
def draw_string_collection(layout, owner, collection_name):
column = layout.column(align=True)
collection = getattr(owner, collection_name)
for i in range(len(collection)):
if i == 0:
row = draw_prop_on_new_row(
column,
collection[i],
"name",
align=True,
text=f"{owner.bl_rna.properties[collection_name].name}")
add_op = row.operator(AddOrRemoveElementFromCollection.bl_idname, icon="ADD", text="")
add_op.operation = "+"
add_op.collection_path = collection.path_from_id()
else:
row = draw_prop_on_new_row(column, collection[i], "name", align=True, text=f"#{i + 1}")
rem_op = row.operator(AddOrRemoveElementFromCollection.bl_idname, icon="REMOVE", text="")
rem_op.operation = "-"
rem_op.collection_path = collection.path_from_id()
rem_op.selected_item_idx = i
def draw_prop_on_new_row(layout, owner, attribute, align=False, **kwargs):
row = layout.row(align=align)
row.prop(owner, attribute, **kwargs)
return row
def draw_roles_ui(box, assigned_object_id, roles, context):
props = context.scene.BIMOwnerProperties
row = box.row(align=True)
row.label(text="Roles")
row.operator("bim.add_role", icon="ADD", text="").assigned_object_id = assigned_object_id
@@ -14,15 +43,12 @@ def draw_roles_ui(box, assigned_object_id, roles):
if props.active_role_id == role_id:
blender_role = props.role
box2 = box.box()
row = box2.row(align=True)
row.prop(blender_role, "name", icon="MOD_CLOTH", text="")
row = draw_prop_on_new_row(box2, blender_role, "name", align=True, icon="MOD_CLOTH", text="")
row.operator("bim.edit_role", icon="CHECKMARK", text="")
row.operator("bim.disable_editing_role", icon="X", text="")
if blender_role.name == "USERDEFINED":
row = box2.row()
row.prop(blender_role, "user_defined_role")
row = box2.row()
row.prop(blender_role, "description")
draw_prop_on_new_row(box2, blender_role, "user_defined_role")
draw_prop_on_new_row(box2, blender_role, "description")
else:
row = box.row(align=True)
row.label(text=role["UserDefinedRole"] or role["Role"])
@@ -30,8 +56,8 @@ def draw_roles_ui(box, assigned_object_id, roles):
row.operator("bim.remove_role", icon="X", text="").role_id = role_id
def draw_addresses_ui(box, assigned_object_id, addresses, file):
props = bpy.context.scene.BIMOwnerProperties
def draw_addresses_ui(box, assigned_object_id, addresses, file, context):
props = context.scene.BIMOwnerProperties
row = box.row(align=True)
row.label(text="Addresses")
op = row.operator("bim.add_address", icon="LINK_BLEND", text="")
@@ -45,45 +71,29 @@ def draw_addresses_ui(box, assigned_object_id, addresses, file):
if props.active_address_id == address_id:
blender_address = props.address
box2 = box.box()
row = box2.row(align=True)
row.prop(blender_address, "purpose", icon="MOD_CLOTH", text="")
row = draw_prop_on_new_row(box2, blender_address, "purpose", align=True, icon="MOD_CLOTH", text="")
row.operator("bim.edit_address", icon="CHECKMARK", text="")
row.operator("bim.disable_editing_address", icon="X", text="")
if blender_address.purpose == "USERDEFINED":
row = box2.row()
row.prop(blender_address, "user_defined_purpose")
row = box2.row()
row.prop(blender_address, "description")
draw_prop_on_new_row(box2, blender_address, "user_defined_purpose")
draw_prop_on_new_row(box2, blender_address, "description")
if address["type"] == "IfcTelecomAddress":
row = box2.row()
row.prop(blender_address, "telephone_numbers")
row = box2.row()
row.prop(blender_address, "facsimile_numbers")
row = box2.row()
row.prop(blender_address, "pager_number")
row = box2.row()
row.prop(blender_address, "electronic_mail_addresses")
row = box2.row()
row.prop(blender_address, "www_home_page_url")
if file.schema != "IFC2X3":
row = box2.row()
row.prop(blender_address, "messaging_ids")
draw_string_collection(box2, blender_address, "telephone_numbers")
draw_string_collection(box2, blender_address, "facsimile_numbers")
draw_prop_on_new_row(box2, blender_address, "pager_number")
draw_string_collection(box2, blender_address, "electronic_mail_addresses")
draw_prop_on_new_row(box2, blender_address, "www_home_page_url")
if file.schema != "IFC2X3":
draw_string_collection(box2, blender_address, "messaging_ids")
elif address["type"] == "IfcPostalAddress":
row = box2.row()
row.prop(blender_address, "internal_location")
row = box2.row()
row.prop(blender_address, "address_lines")
row = box2.row()
row.prop(blender_address, "postal_box")
row = box2.row()
row.prop(blender_address, "town")
row = box2.row()
row.prop(blender_address, "region")
row = box2.row()
row.prop(blender_address, "postal_code")
row = box2.row()
row.prop(blender_address, "country")
draw_prop_on_new_row(box2, blender_address, "internal_location")
draw_string_collection(box2, blender_address, "address_lines")
draw_prop_on_new_row(box2, blender_address, "postal_box")
draw_prop_on_new_row(box2, blender_address, "town")
draw_prop_on_new_row(box2, blender_address, "region")
draw_prop_on_new_row(box2, blender_address, "postal_code")
draw_prop_on_new_row(box2, blender_address, "country")
else:
row = box.row(align=True)
row.label(text=address["type"])
@@ -91,7 +101,6 @@ def draw_addresses_ui(box, assigned_object_id, addresses, file):
row.operator("bim.remove_address", icon="X", text="").address_id = address_id
class BIM_PT_people(Panel):
bl_label = "IFC People"
bl_idname = "BIM_PT_people"
@@ -120,23 +129,16 @@ class BIM_PT_people(Panel):
if props.active_person_id == person_id:
blender_person = props.person
box = self.layout.box()
row = box.row(align=True)
row.prop(blender_person, "name", icon="USER", text="")
row = draw_prop_on_new_row(box, blender_person, "name", align=True, icon="USER", text="")
row.operator("bim.edit_person", icon="CHECKMARK", text="")
row.operator("bim.disable_editing_person", icon="X", text="")
row = box.row()
row.prop(blender_person, "family_name")
row = box.row()
row.prop(blender_person, "given_name")
row = box.row()
row.prop(blender_person, "middle_names")
row = box.row()
row.prop(blender_person, "prefix_titles")
row = box.row()
row.prop(blender_person, "suffix_titles")
draw_roles_ui(box, person_id, person["Roles"])
draw_addresses_ui(box, person_id, person["Addresses"], self.file)
draw_prop_on_new_row(box, blender_person, "family_name")
draw_prop_on_new_row(box, blender_person, "given_name")
draw_string_collection(box, blender_person, "middle_names")
draw_string_collection(box, blender_person, "prefix_titles")
draw_string_collection(box, blender_person, "suffix_titles")
draw_roles_ui(box, person_id, person["Roles"], context)
draw_addresses_ui(box, person_id, person["Addresses"], self.file, context)
else:
row = self.layout.row(align=True)
name = person["Id"] if self.file.schema == "IFC2X3" else person["Identification"]
@@ -183,14 +185,12 @@ class BIM_PT_organisations(Panel):
row = box.row(align=True)
row.prop(blender_organisation, "name", icon="USER", text="")
row.operator("bim.edit_organisation", icon="CHECKMARK", text="")
row.operator("bim.disable_editing_organisation", icon="X", text="")
row = box.row()
row.prop(blender_organisation, "identification")
row = box.row()
row.prop(blender_organisation, "description")
row.operator("bim.disable_editing_organisation", icon="X", text="")
draw_prop_on_new_row(box, blender_organisation, "identification")
draw_prop_on_new_row(box, blender_organisation, "description")
draw_roles_ui(box, organisation_id, organisation["Roles"])
draw_addresses_ui(box, organisation_id, organisation["Addresses"], self.file)
draw_roles_ui(box, organisation_id, organisation["Roles"], context)
draw_addresses_ui(box, organisation_id, organisation["Addresses"], self.file, context)
else:
row = self.layout.row(align=True)
row.label(text=organisation["Name"])
@@ -224,11 +224,9 @@ class BIM_PT_owner(Panel):
if not Data.people:
self.layout.label(text="No people found.")
else:
row = self.layout.row()
row.prop(props, "user_person")
draw_prop_on_new_row(self.layout, props, "user_person")
if not Data.organisations:
self.layout.label(text="No organisations found.")
else:
row = self.layout.row()
row.prop(props, "user_organisation")
draw_prop_on_new_row(self.layout, props, "user_organisation")
@@ -40,6 +40,11 @@ class ExecuteIfcPatch(bpy.types.Operator):
bl_label = "Execute IFCPatch"
file_format: bpy.props.StringProperty()
@classmethod
def poll(cls, context):
input_file = context.scene.BIMPatchProperties.ifc_patch_input
return os.path.isfile(input_file) and "ifc" in os.path.splitext(input_file)[1]
def execute(self, context):
import ifcpatch
@@ -0,0 +1,9 @@
classes = ()
def register():
pass
def unregister():
pass
@@ -29,17 +29,17 @@ class CreateProject(bpy.types.Operator):
return {"FINISHED"}
IfcStore.file = ifcopenshell.api.run(
"project.create_file", **{"version": bpy.context.scene.BIMProperties.export_schema}
"project.create_file", **{"version": context.scene.BIMProperties.export_schema}
)
self.file = IfcStore.get_file()
bpy.ops.bim.add_person()
bpy.ops.bim.add_organisation()
project = bpy.data.objects.new("My Project", None)
site = bpy.data.objects.new("My Site", None)
building = bpy.data.objects.new("My Building", None)
building_storey = bpy.data.objects.new("Ground Floor", None)
project = bpy.data.objects.new(self.get_name("IfcProject", "My Project"), None)
site = bpy.data.objects.new(self.get_name("IfcSite", "My Site"), None)
building = bpy.data.objects.new(self.get_name("IfcBuilding", "My Building"), None)
building_storey = bpy.data.objects.new(self.get_name("IfcBuildingStorey", "My Storey"), None)
bpy.ops.bim.assign_class(obj=project.name, ifc_class="IfcProject")
bpy.ops.bim.assign_unit()
@@ -49,7 +49,7 @@ class CreateProject(bpy.types.Operator):
bpy.ops.bim.add_subcontext(context="Plan")
bpy.ops.bim.add_subcontext(context="Plan", subcontext="Annotation", target_view="PLAN_VIEW")
bpy.context.scene.BIMProperties.contexts = str(
context.scene.BIMProperties.contexts = str(
ifcopenshell.util.representation.get_context(self.file, "Model", "Body", "MODEL_VIEW").id()
)
@@ -62,6 +62,14 @@ class CreateProject(bpy.types.Operator):
return {"FINISHED"}
def get_name(self, ifc_class, name):
if not bpy.data.objects.get(f"{ifc_class}/{name}"):
return name
i = 2
while bpy.data.objects.get(f"{ifc_class}/{name} {i}"):
i += 1
return f"{name} {i}"
def rollback(self, data):
IfcStore.file = None
@@ -89,7 +97,7 @@ class CreateProjectLibrary(bpy.types.Operator):
return {"FINISHED"}
IfcStore.file = ifcopenshell.api.run(
"project.create_file", **{"version": bpy.context.scene.BIMProperties.export_schema}
"project.create_file", **{"version": context.scene.BIMProperties.export_schema}
)
self.file = IfcStore.get_file()
@@ -164,9 +172,10 @@ class RefreshLibrary(bpy.types.Operator):
self.props.active_library_element = ""
types = IfcStore.library_file.wrapped_data.types_with_super()
if "IfcTypeProduct" in types:
new = self.props.library_elements.add()
new.name = "IfcTypeProduct"
for importable_type in ["IfcTypeProduct", "IfcMaterial", "IfcCostSchedule"]:
if importable_type in types:
new = self.props.library_elements.add()
new.name = importable_type
return {"FINISHED"}
@@ -193,7 +202,9 @@ class ChangeLibraryElement(bpy.types.Operator):
new.ifc_definition_id = element.id()
if IfcStore.library_file.schema == "IFC2X3" or not IfcStore.library_file.by_type("IfcProjectLibrary"):
new.is_declared = False
elif element.HasContext and element.HasContext[0].RelatingContext.is_a("IfcProjectLibrary"):
elif getattr(element, "HasContext", None) and element.HasContext[0].RelatingContext.is_a(
"IfcProjectLibrary"
):
new.is_declared = True
else:
for ifc_class in ifc_classes:
@@ -318,14 +329,28 @@ class AppendLibraryElement(bpy.types.Operator):
library=IfcStore.library_file,
element=IfcStore.library_file.by_id(self.definition),
)
self.import_type_from_ifc(element)
if not element:
return {"FINISHED"}
if element.is_a("IfcTypeProduct"):
self.import_type_from_ifc(element, context)
elif element.is_a("IfcMaterial"):
self.import_material_from_ifc(element, context)
blenderbim.bim.handler.purge_module_data()
return {"FINISHED"}
def import_type_from_ifc(self, element):
def import_material_from_ifc(self, element, context):
self.file = IfcStore.get_file()
logger = logging.getLogger("ImportIFC")
ifc_import_settings = import_ifc.IfcImportSettings.factory(bpy.context, IfcStore.path, logger)
ifc_import_settings = import_ifc.IfcImportSettings.factory(context, IfcStore.path, logger)
ifc_importer = import_ifc.IfcImporter(ifc_import_settings)
ifc_importer.file = self.file
blender_material = ifc_importer.create_material(element)
self.import_material_styles(blender_material, element, ifc_importer)
def import_type_from_ifc(self, element, context):
self.file = IfcStore.get_file()
logger = logging.getLogger("ImportIFC")
ifc_import_settings = import_ifc.IfcImportSettings.factory(context, IfcStore.path, logger)
type_collection = bpy.data.collections.get("Types")
if not type_collection:
@@ -338,9 +363,37 @@ class AppendLibraryElement(bpy.types.Operator):
ifc_importer = import_ifc.IfcImporter(ifc_import_settings)
ifc_importer.file = self.file
ifc_importer.type_collection = type_collection
self.import_type_materials(element, ifc_importer)
self.import_type_styles(element, ifc_importer)
ifc_importer.create_type_product(element)
ifc_importer.place_objects_in_spatial_tree()
def import_type_materials(self, element, ifc_importer):
for rel in element.HasAssociations:
if not rel.is_a("IfcRelAssociatesMaterial"):
continue
for material in [e for e in self.file.traverse(rel) if e.is_a("IfcMaterial")]:
if IfcStore.get_element(material.id()):
continue
blender_material = ifc_importer.create_material(material)
self.import_material_styles(blender_material, material, ifc_importer)
def import_type_styles(self, element, ifc_importer):
for representation_map in element.RepresentationMaps or []:
for element in self.file.traverse(representation_map):
if not element.is_a("IfcRepresentationItem") or not element.StyledByItem:
continue
for element2 in self.file.traverse(element.StyledByItem[0]):
if element2.is_a("IfcSurfaceStyle") and not IfcStore.get_element(element2.id()):
ifc_importer.create_style(element2)
def import_material_styles(self, blender_material, material, ifc_importer):
if not material.HasRepresentation:
return
for element in self.file.traverse(material.HasRepresentation[0]):
if element.is_a("IfcSurfaceStyle") and not IfcStore.get_element(element.id()):
ifc_importer.create_style(element, blender_material)
class EnableEditingHeader(bpy.types.Operator):
bl_idname = "bim.enable_editing_header"
@@ -7,6 +7,7 @@ import ifcopenshell.util.attribute
import blenderbim.bim.schema
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.pset.data import Data
from ifcopenshell.api.cost.data import Data as CostData
from blenderbim.bim.module.pset.qto_calculator import QtoCalculator
@@ -16,7 +17,7 @@ class TogglePsetExpansion(bpy.types.Operator):
pset_id: bpy.props.IntProperty()
def execute(self, context):
obj = bpy.context.active_object
obj = context.active_object
data = Data.psets if self.pset_id in Data.psets else Data.qtos
data[self.pset_id]["is_expanded"] = not data[self.pset_id]["is_expanded"]
return {"FINISHED"}
@@ -195,6 +196,7 @@ class EditPset(bpy.types.Operator):
"pset": self.file.by_id(pset_id),
"name": props.active_pset_name,
"properties": properties,
"pset_template": blenderbim.bim.schema.ifc.psetqto.get_by_name(props.active_pset_name),
},
)
else:
@@ -210,6 +212,7 @@ class EditPset(bpy.types.Operator):
"properties": properties,
},
)
CostData.purge()
Data.load(IfcStore.get_file(), oprops.ifc_definition_id)
bpy.ops.bim.disable_pset_editing(obj=self.obj, obj_type=self.obj_type)
return {"FINISHED"}
@@ -294,7 +297,7 @@ class AddQto(bpy.types.Operator):
def _execute(self, context):
self.file = IfcStore.get_file()
obj = bpy.context.active_object
obj = context.active_object
oprops = obj.BIMObjectProperties
props = obj.PsetProperties
ifcopenshell.api.run(
@@ -317,23 +320,23 @@ class GuessQuantity(bpy.types.Operator):
def execute(self, context):
self.qto_calculator = QtoCalculator()
obj = bpy.context.active_object
obj = context.active_object
prop = obj.PsetProperties.properties.get(self.prop)
prop.float_value = self.guess_quantity(obj)
prop.float_value = self.guess_quantity(obj, context)
return {"FINISHED"}
def guess_quantity(self, obj):
def guess_quantity(self, obj, context):
quantity = self.qto_calculator.guess_quantity(self.prop, [p.name for p in obj.PsetProperties.properties], obj)
if "area" in self.prop.lower():
if bpy.context.scene.BIMProperties.area_unit:
prefix, name = self.get_prefix_name(bpy.context.scene.BIMProperties.area_unit)
if context.scene.BIMProperties.area_unit:
prefix, name = self.get_prefix_name(context.scene.BIMProperties.area_unit)
quantity = ifcopenshell.util.unit.convert(quantity, None, "SQUARE_METRE", prefix, name)
elif "volume" in self.prop.lower():
if bpy.context.scene.BIMProperties.volume_unit:
prefix, name = self.get_prefix_name(bpy.context.scene.BIMProperties.volume_unit)
if context.scene.BIMProperties.volume_unit:
prefix, name = self.get_prefix_name(context.scene.BIMProperties.volume_unit)
quantity = ifcopenshell.util.unit.convert(quantity, None, "CUBIC_METRE", prefix, name)
else:
prefix, name = self.get_blender_prefix_name()
prefix, name = self.get_blender_prefix_name(context)
quantity = ifcopenshell.util.unit.convert(quantity, None, "METRE", prefix, name)
return round(quantity, 3)
@@ -342,13 +345,14 @@ class GuessQuantity(bpy.types.Operator):
return value.split("/")
return None, value
def get_blender_prefix_name(self):
if bpy.context.scene.unit_settings.system == "IMPERIAL":
if bpy.context.scene.unit_settings.length_unit == "INCHES":
def get_blender_prefix_name(self, context):
unit_settings = context.scene.unit_settings
if unit_settings.system == "IMPERIAL":
if unit_settings.length_unit == "INCHES":
return None, "inch"
elif bpy.context.scene.unit_settings.length_unit == "FEET":
elif unit_settings.length_unit == "FEET":
return None, "foot"
elif bpy.context.scene.unit_settings.system == "METRIC":
if bpy.context.scene.unit_settings.length_unit == "METERS":
elif unit_settings.system == "METRIC":
if unit_settings.length_unit == "METERS":
return None, "METRE"
return bpy.context.scene.unit_settings.length_unit[0 : -len("METERS")], "METRE"
return unit_settings.length_unit[0 : -len("METERS")], "METRE"
@@ -1,7 +1,8 @@
import bpy
import blenderbim.bim.schema
from blenderbim.bim.prop import Attribute
from ifcopenshell.api.pset.data import Data
import blenderbim.bim.schema
from blenderbim.bim.ifc import IfcStore
from bpy.types import PropertyGroup
from bpy.props import (
PointerProperty,
@@ -29,16 +30,17 @@ def purge():
def getPsetNames(self, context):
global psetnames
obj = context.active_object
if "/" in obj.name:
ifc_class = obj.name.split("/")[0]
if ifc_class not in psetnames:
psets = blenderbim.bim.schema.ifc.psetqto.get_applicable(ifc_class, pset_only=True)
psetnames[ifc_class] = [(p.Name, p.Name, "") for p in psets]
assigned_names = [
Data.psets[p]["Name"] for p in Data.products[obj.BIMObjectProperties.ifc_definition_id]["psets"]
]
return [p for p in psetnames[ifc_class] if p[0] not in assigned_names]
return []
if not obj.BIMObjectProperties.ifc_definition_id:
return []
element = IfcStore.get_file().by_id(obj.BIMObjectProperties.ifc_definition_id)
ifc_class = element.is_a()
if ifc_class not in psetnames:
psets = blenderbim.bim.schema.ifc.psetqto.get_applicable(ifc_class, pset_only=True)
psetnames[ifc_class] = [(p.Name, p.Name, "") for p in psets]
assigned_names = [
Data.psets[p]["Name"] for p in Data.products[obj.BIMObjectProperties.ifc_definition_id]["psets"]
]
return [p for p in psetnames[ifc_class] if p[0] not in assigned_names]
def getMaterialPsetNames(self, context):
@@ -122,8 +122,8 @@ class BIM_PT_object_psets(Panel):
op.obj = context.active_object.name
op.obj_type = "Object"
for pset_id in Data.products[oprops.ifc_definition_id]["psets"]:
pset = Data.psets[pset_id]
psets = [(pset_id, Data.psets[pset_id]) for pset_id in Data.products[oprops.ifc_definition_id]["psets"]]
for pset_id, pset in sorted(psets, key = lambda v: v[1]["Name"]):
draw_psetqto_ui(context, pset_id, pset, props, self.layout, "Object")
# TODO reimplement. See #1222.
@@ -165,8 +165,8 @@ class BIM_PT_object_qtos(Panel):
row.prop(props, "qto_name", text="")
row.operator("bim.add_qto", icon="ADD", text="")
for qto_id in Data.products[oprops.ifc_definition_id]["qtos"]:
qto = Data.qtos[qto_id]
qtos = [(qto_id, Data.qtos[qto_id]) for qto_id in Data.products[oprops.ifc_definition_id]["qtos"]]
for qto_id, qto in sorted(qtos, key = lambda v: v[1]["Name"]):
draw_psetqto_ui(context, qto_id, qto, props, self.layout, "Object")
@@ -207,6 +207,6 @@ class BIM_PT_material_psets(Panel):
op.obj = context.active_object.active_material.name
op.obj_type = "Material"
for pset_id in Data.products[oprops.ifc_definition_id]["psets"]:
pset = Data.psets[pset_id]
psets = [(pset_id, Data.psets[pset_id]) for pset_id in Data.products[oprops.ifc_definition_id]["psets"]]
for pset_id, pset in sorted(psets, key = lambda v: v[1]["Name"]):
draw_psetqto_ui(context, pset_id, pset, props, self.layout, "Material")
@@ -1,6 +1,8 @@
import bpy
import ifcopenshell
import ifcopenshell.api
import blenderbim.bim.schema
import blenderbim.bim.handler
from blenderbim.bim.module.pset_template.prop import updatePsetTemplateFiles, updatePsetTemplates
from ifcopenshell.api.pset_template.data import Data
from blenderbim.bim.ifc import IfcStore
@@ -165,6 +167,8 @@ class SavePsetTemplateFile(bpy.types.Operator):
def execute(self, context):
IfcStore.pset_template_file.write(IfcStore.pset_template_path)
blenderbim.bim.handler.purge_module_data()
blenderbim.bim.schema.reload()
return {"FINISHED"}
@@ -14,7 +14,7 @@ def calculate_volume(obj):
return result
def calculate_formwork_area(objs):
def calculate_formwork_area(objs, context):
"""
Formwork is defined as the surface area required to cover all exposed
surfaces of one or more objects, excluding top surfaces (i.e. that have a
@@ -27,7 +27,7 @@ def calculate_formwork_area(objs):
new_obj = obj.copy()
new_obj.data = obj.data.copy()
new_obj.animation_data_clear()
bpy.context.collection.objects.link(new_obj)
context.collection.objects.link(new_obj)
copied_objs.append(new_obj)
context_override = {}
@@ -53,7 +53,7 @@ def calculate_formwork_area(objs):
else:
modifier.octree_depth = 5
mesh = copied_objs[0].evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh()
mesh = copied_objs[0].evaluated_get(context.evaluated_depsgraph_get()).to_mesh()
for polygon in mesh.polygons:
if polygon.normal.z > 0.5:
continue
@@ -14,13 +14,13 @@ class CalculateEdgeLengths(bpy.types.Operator):
def execute(self, context):
result = 0
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
if not obj.data or not obj.data.edges:
continue
for edge in obj.data.edges:
if edge.select:
result += (obj.data.vertices[edge.vertices[1]].co - obj.data.vertices[edge.vertices[0]].co).length
bpy.context.scene.BIMQtoProperties.qto_result = str(round(result, 3))
context.scene.BIMQtoProperties.qto_result = str(round(result, 3))
return {"FINISHED"}
@@ -31,13 +31,13 @@ class CalculateFaceAreas(bpy.types.Operator):
def execute(self, context):
result = 0
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
if not obj.data or not obj.data.polygons:
continue
for polygon in obj.data.polygons:
if polygon.select:
result += polygon.area
bpy.context.scene.BIMQtoProperties.qto_result = str(round(result, 3))
context.scene.BIMQtoProperties.qto_result = str(round(result, 3))
return {"FINISHED"}
@@ -48,14 +48,14 @@ class CalculateObjectVolumes(bpy.types.Operator):
def execute(self, context):
result = 0
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
if not obj.data or not isinstance(obj.data, bpy.types.Mesh):
continue
bm = bmesh.new()
bm.from_mesh(obj.data)
result += bm.calc_volume()
bm.free()
bpy.context.scene.BIMQtoProperties.qto_result = str(round(result, 3))
context.scene.BIMQtoProperties.qto_result = str(round(result, 3))
return {"FINISHED"}
@@ -65,16 +65,16 @@ class ExecuteQtoMethod(bpy.types.Operator):
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
props = bpy.context.scene.BIMQtoProperties
props = context.scene.BIMQtoProperties
result = 0
if props.qto_methods == "HEIGHT":
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
result += helper.calculate_height(obj)
elif props.qto_methods == "VOLUME":
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
result += helper.calculate_volume(obj)
elif props.qto_methods == "FORMWORK":
result = helper.calculate_formwork_area(bpy.context.selected_objects)
result = helper.calculate_formwork_area(context.selected_objects, context)
props.qto_result = str(round(result, 3))
return {"FINISHED"}
@@ -88,9 +88,9 @@ class QuantifyObjects(bpy.types.Operator):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
props = bpy.context.scene.BIMQtoProperties
props = context.scene.BIMQtoProperties
self.file = IfcStore.get_file()
for obj in bpy.context.selected_objects:
for obj in context.selected_objects:
if not obj.BIMObjectProperties.ifc_definition_id:
continue
result = 0
@@ -99,7 +99,7 @@ class QuantifyObjects(bpy.types.Operator):
elif props.qto_methods == "VOLUME":
result = helper.calculate_volume(obj)
elif props.qto_methods == "FORMWORK":
result = helper.calculate_formwork_area([obj])
result = helper.calculate_formwork_area([obj], context)
if not result:
continue
result = round(result, 3)
@@ -14,6 +14,9 @@ classes = (
operator.ContractResource,
operator.AssignResource,
operator.UnassignResource,
operator.EnableEditingResourceTime,
operator.EditResourceTime,
operator.DisableEditingResourceTime,
prop.Resource,
prop.BIMResourceProperties,
prop.BIMResourceTreeProperties,
@@ -3,6 +3,11 @@ import json
import ifcopenshell.api
from blenderbim.bim.ifc import IfcStore
from ifcopenshell.api.resource.data import Data
import blenderbim.bim.helper
import blenderbim.bim.module.sequence.helper as helper
import time
from datetime import datetime
import isodate
class LoadResources(bpy.types.Operator):
@@ -50,6 +55,7 @@ class EnableEditingResource(bpy.types.Operator):
self.props.active_resource_id = self.resource
while len(self.props.resource_attributes) > 0:
self.props.resource_attributes.remove(0)
self.props.editing_resource_type = "ATTRIBUTES"
self.enable_editing_resource()
return {"FINISHED"}
@@ -72,6 +78,7 @@ class EnableEditingResource(bpy.types.Operator):
new.enum_value = data[attribute.name()]
class LoadResourceProperties(bpy.types.Operator):
bl_idname = "bim.load_resource_properties"
bl_label = "Load Resource Properties"
@@ -98,6 +105,7 @@ class DisableEditingResource(bpy.types.Operator):
def execute(self, context):
context.scene.BIMResourceProperties.active_resource_id = 0
context.scene.BIMResourceProperties.active_task_time_id = 0
return {"FINISHED"}
@@ -143,15 +151,7 @@ class EditResource(bpy.types.Operator):
def _execute(self, context):
props = context.scene.BIMResourceProperties
attributes = {}
for attribute in props.resource_attributes:
if attribute.is_null:
attributes[attribute.name] = None
else:
if attribute.data_type == "string":
attributes[attribute.name] = attribute.string_value
elif attribute.data_type == "enum":
attributes[attribute.name] = attribute.enum_value
attributes = blenderbim.bim.helper.export_attributes(props.resource_attributes)
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"resource.edit_resource",
@@ -230,7 +230,7 @@ class AssignResource(bpy.types.Operator):
def _execute(self, context):
related_objects = (
[bpy.data.objects.get(self.related_object)] if self.related_object else bpy.context.selected_objects
[bpy.data.objects.get(self.related_object)] if self.related_object else context.selected_objects
)
for related_object in related_objects:
self.file = IfcStore.get_file()
@@ -253,7 +253,7 @@ class UnassignResource(bpy.types.Operator):
def execute(self, context):
related_objects = (
[bpy.data.objects.get(self.related_object)] if self.related_object else bpy.context.selected_objects
[bpy.data.objects.get(self.related_object)] if self.related_object else context.selected_objects
)
for related_object in related_objects:
self.file = IfcStore.get_file()
@@ -265,3 +265,87 @@ class UnassignResource(bpy.types.Operator):
)
Data.load(self.file)
return {"FINISHED"}
class EnableEditingResourceTime(bpy.types.Operator):
bl_idname = "bim.enable_editing_resource_time"
bl_label = "Enable Editing Resource Usage"
bl_options = {"REGISTER", "UNDO"}
resource: bpy.props.IntProperty()
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
props = context.scene.BIMResourceProperties
self.file = IfcStore.get_file()
resource_time_id = Data.resources[self.resource]["Usage"] or self.add_resource_time().id()
while len(props.resource_time_attributes) > 0:
props.resource_time_attributes.remove(0)
data = Data.resource_times[resource_time_id]
blenderbim.bim.helper.import_attributes("IfcResourceTime", props.resource_time_attributes, data, self.import_attributes)
props.active_resource_time_id = resource_time_id
props.active_resource_id = self.resource
props.editing_resource_type = "USAGE"
return {"FINISHED"}
def import_attributes(self, name, prop, data):
if prop.data_type == "string":
if isinstance(data[name], datetime):
prop.string_value = "" if prop.is_null else data[name].isoformat()
return True
elif isinstance(data[name], isodate.Duration):
prop.string_value = (
"" if prop.is_null else ifcopenshell.util.date.datetime2ifc(data[name], "IfcDuration")
)
return True
def add_resource_time(self):
resource_time = ifcopenshell.api.run("resource.add_resource_time", self.file, resource=self.file.by_id(self.resource))
Data.load(self.file)
return resource_time
class DisableEditingResourceTime(bpy.types.Operator):
bl_idname = "bim.disable_editing_resource_time"
bl_label = "Disable Editing Resource Time"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
context.scene.BIMResourceProperties.active_resource_time_id = 0
bpy.ops.bim.disable_editing_resource()
return {"FINISHED"}
class EditResourceTime(bpy.types.Operator):
bl_idname = "bim.edit_resource_time"
bl_label = "Edit Resource Usage"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
return IfcStore.execute_ifc_operator(self, context)
def _execute(self, context):
self.props = context.scene.BIMResourceProperties
attributes = blenderbim.bim.helper.export_attributes(self.props.resource_time_attributes, self.export_attributes)
self.file = IfcStore.get_file()
ifcopenshell.api.run(
"resource.edit_resource_time",
self.file,
**{"resource_time": self.file.by_id(self.props.active_resource_time_id), "attributes": attributes},
)
Data.load(self.file)
bpy.ops.bim.disable_editing_resource_time()
bpy.ops.bim.load_resource_properties(resource=self.props.active_resource_id)
return {"FINISHED"}
def export_attributes(self, attributes, prop):
if "Start" in prop.name or "Finish" in prop.name or prop.name == "StatusTime":
attributes[prop.name] = helper.parse_datetime(prop.string_value)
return True
elif prop.name =="LevelingDelay" or "Work" in prop.name:
attributes[prop.name] = helper.parse_duration(prop.string_value)
return True

Some files were not shown because too many files have changed in this diff Show More