feature: chat (#36)

* fix(config): load config on demand in get/set instead of asserting

* feat(chat): implement in-game chat box with UTF-8 support

- Add ChatMessage struct and ChatBox widget for displaying and sending messages
- Introduce split_utf8() in text_tools for splitting UTF-8 strings by character count
- Add TimeTools utility (get_time_ticks) for message timestamps
- Update TextField with start_typing/stop_typing methods and set_typing()
- Integrate text input handling in WorldScene and WorldUIManager for chat
- Add utf8cpp library for robust UTF-8 validation and processing
- Add ChatBox rendering and input logic (src/ui/chat_box.cpp)
- Register ChatBox source in CMakeLists.txt
- Fix Renderer::render_lable to skip rendering if VAO is null
- Update credits to include utf8cpp library

* fix(ui): correct chat box layout with dynamic height and bottom anchor

* feat(chat): implement client-server chat messaging

Add protobuf definition for ChatMsg, new packet ID CHAT_MSG (4001), and
handle sending/receiving chat messages on both client and server side.
Wire up UI components (ChatBox, TextField) to allow message input and
display, including a message queue in ClientWorld for thread-safe
processing. Also add default initialization for ChatMessage::time.

* feat(chat): distinguish between send and cancel in chat input

* feat(ui): add background to Label widget and refactor debug overlay

* refactor(ui): decouple ChatBox from image dependencies, allow custom TextField backgrounds

TextField's background is now a generic `Widget` pointer, enabling use of any widget (e.g., `Rect`, `Image`) as background. `ChatBox` no longer creates its own `TextField`; it accepts one via `set_text_field`. Removed `set_d_image` and `set_default_image` in favor of `set_background`. Added a shared default image constant in `default_image.hpp`. Updated `host_game_ui.cpp`, `join_game_ui.cpp`, and `world_ui_manager.cpp` to construct backgrounds accordingly.

* refactor(ui): move width, height, and fill properties to base Widget

Consolidate width, height, and fill (fill_parent, fill_width, fill_height) into the base Widget class. Replace per-widget set_fill(bool) with set_fill_parent(bool), set_fill_width(bool), and set_fill_height(bool).

* refactor(ui): generalize Label background, add ChatBox width method

* feat(chat): implement message expiration after 5 seconds

* feat(ui): add word wrap for chat messages with font width measurement

* feat(audio): implement voice chat using Opus codec

Add voice chat support with Opus encoding/decoding, push-to-talk (V key), and new audio recording infrastructure.

* feat(audio): implement voice chat with Opus codec and streaming audio source

Add AudioStreamSource for continuous PCM playback. Refactor voice send/receive to encode with Opus and stream to a dedicated source instead of per-frame sources. Enable voice transmission over network.

* feat(audio): add spatial voice source with underwater effects

Update voice source to support spatial positioning, low-pass filter, and reverb effect for underwater immersion. Adjust source pool size and low-pass filter parameter. Correct receive_voice parameter type.

* feat(settings): add player voice volume and voice input type options

- Add player voice volume slider and voice input type combo in settings UI.
- Add localization strings for player voice and voice input types.
- Add config overloads for const char* default values.
- Implement voice input types (PTT, always, off) in world scene.
- Refactor WorldScene member order and add load_config method.
- Update audio engine to use player voice volume.
- Downgrade some logging to debug.

* fix(event): delegate error UI events to each handler

Move error UI event check from top of handle_event into each individual
event handler (mouse_move, mouse_button, mouse_wheel, key, text_input).
Also flatten window resize dispatch: all sub-handlers are called regardless
of previous handler return values, and the method always returns false.

* feat(chat): add colored system messages for player join/exit

* chore(logging): reduce verbosity for audio loading and input events

* fix(settings): fix typo in config key "vloume"

* feat(ui): add microphone icon when recording voice

* feat(voice): limit voice message range to 48 units

* chore(logging): downgrade text input log level to debug

* feat(credits): add license identifiers and reorganize license files

* feat: add sensitive word filter for chat messages

Implement AC automaton-based filtering using a sensitive lexicon loaded from a JSON asset file. The filter is applied to both player names and chat messages before broadcasting, and can be toggled via the `sensitive_filter` config option.

* feat(server): add config option to disable voice chat

* fix: correct utf8 validation, add missing include, remove debug log
This commit is contained in:
zhenyan121
2026-07-21 10:21:05 +08:00
committed by GitHub
parent 0f731530da
commit 45d2c8234a
90 changed files with 3931 additions and 357 deletions

View File

@@ -147,6 +147,7 @@ target_link_libraries(${PROJECT_NAME}
zstd::zstd
OpenAL::OpenAL
harfbuzz::harfbuzz
Opus::Opus
$<$<PLATFORM_ID:Windows>:ws2_32>
)

File diff suppressed because one or more lines are too long

View File

@@ -17,11 +17,15 @@
"settings.distance": "Distance: {distance}",
"settings.music_volume": "Music: {music}",
"settings.sfx_volume": "SFX: {sfx}",
"settings.player_voice": "Player Voice: {volume}",
"settings.fullscreen": "fullscreen: {state}",
"settings.aniso": "Aniso: {aniso}",
"settings.vsync": "V-Sync: {state}",
"settings.language": "Language: {lang}",
"settings.restart_game_info": "You need to restart the game to apply this changes.",
"settings.voice_input": "Voice Input: {type}",
"voice_input.ptt": "PTT",
"voice_input.always": "always",
"common.on": "on",
"common.off": "off",
"hostgame.create_a_new_world": "Create A New World",
@@ -30,5 +34,6 @@
"hostgame.create_world": "Create World",
"joingame.join_a_world": "Join A World",
"joingame.server_ip": "Server Ip",
"joingame.join_world": "Join World"
"joingame.join_world": "Join World",
"error.disable_voice": "Server Disable Voice Chat"
}

View File

@@ -17,11 +17,15 @@
"settings.distance": "距离:{distance}",
"settings.music_volume": "音乐:{music}",
"settings.sfx_volume": "音效:{sfx}",
"settings.player_voice": "玩家语音:{volume}",
"settings.fullscreen": "全屏:{state}",
"settings.aniso": "各向异性过滤:{aniso}",
"settings.vsync": "垂直同步: {state}",
"settings.language": "语言: {lang}",
"settings.restart_game_info": "您需要重启游戏以应用这些更改。",
"settings.voice_input": "语音输入: {type}",
"voice_input.ptt": "按键通话",
"voice_input.always": "始终",
"common.on": "开",
"common.off": "关",
"hostgame.create_a_new_world": "创建新世界",
@@ -30,5 +34,6 @@
"hostgame.create_world": "创建世界",
"joingame.join_a_world": "加入世界",
"joingame.server_ip": "服务器IP",
"joingame.join_world": "加入世界"
"joingame.join_world": "加入世界",
"error.disable_voice": "服务器已禁用语音聊天"
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 B

View File

@@ -9,7 +9,7 @@ find_package(OpenAL REQUIRED)
find_package(harfbuzz REQUIRED)
find_package(Freetype REQUIRED)
find_package(SDL3 REQUIRED)
find_package(Opus REQUIRED)
# Third-party libraries
FetchContent_Declare(

View File

@@ -0,0 +1,25 @@
include(FindPackageHandleStandardArgs)
find_path(OPUS_INCLUDE_DIR
NAMES opus/opus.h opus.h
)
find_library(OPUS_LIBRARY
NAMES opus
)
find_package_handle_standard_args(
Opus
REQUIRED_VARS
OPUS_INCLUDE_DIR
OPUS_LIBRARY
)
if(Opus_FOUND)
add_library(Opus::Opus UNKNOWN IMPORTED)
set_target_properties(Opus::Opus PROPERTIES
IMPORTED_LOCATION "${OPUS_LIBRARY}"
INTERFACE_INCLUDE_DIRECTORIES "${OPUS_INCLUDE_DIR}"
)
endif()

View File

@@ -1,7 +1,9 @@
#pragma once
#include "Cubed/audio/audio_fade.hpp"
#include "Cubed/audio/audio_recording.hpp"
#include "Cubed/audio/audio_source.hpp"
#include "Cubed/audio/audio_stream_source.hpp"
#include "Cubed/audio/sound_manager.hpp"
#include "Cubed/audio/source_pool.hpp"
#include "Cubed/config.hpp"
@@ -10,13 +12,15 @@
#include <AL/alc.h>
#include <glm/glm.hpp>
#include <memory>
#include <opus/opus.h>
#include <string>
#include <unordered_map>
namespace Cubed {
class ClientWorld;
class NetworkClient;
class AudioEngine {
public:
AudioEngine(Config& config);
AudioEngine(const AudioEngine&) = delete;
@@ -41,11 +45,23 @@ public:
float& bgm_target_volume();
void set_client(std::weak_ptr<NetworkClient> client);
void send_voice(const std::array<int16_t, AudioRecording::FRAME_SAMPLES>&);
void receive_voice(std::span<const char> opus, const glm::vec3& pos);
AudioRecording& audio_recording();
const AudioRecording& audio_recording() const;
private:
using FadeMap = std::unordered_map<std::string, AudioFade>;
bool m_init{false};
ALCdevice* device{nullptr};
ALCcontext* context{nullptr};
OpusEncoder* m_encoder{nullptr};
OpusDecoder* m_decoder{nullptr};
AudioRecording m_recording;
std::weak_ptr<NetworkClient> m_client;
glm::vec3 listener_pos;
std::unique_ptr<AudioSource> m_bgm;
FadeMap m_fade_map;
@@ -56,6 +72,9 @@ private:
bool m_underwater = false;
float m_music_volume = 1.0f;
float m_sfx_volume = 1.0f;
float m_player_voice_volume = 1.0f;
std::unique_ptr<AudioStreamSource> m_voice_source;
std::unique_ptr<AudioFilter> m_low_pass_filter;
std::unique_ptr<AudioEffect> m_underwater_effect;
std::unique_ptr<AudioEffectSlot> m_underwater_slot;

View File

@@ -0,0 +1,33 @@
#pragma once
#include <alc.h>
#include <array>
#include <cstdint>
namespace Cubed {
class AudioEngine;
class AudioRecording {
public:
static constexpr int SAMPLE_RATE = 48000;
static constexpr int FRAME_MS = 20;
static constexpr int FRAME_SAMPLES = SAMPLE_RATE * FRAME_MS / 1000;
AudioRecording(AudioEngine& engine);
AudioRecording(const AudioRecording&) = delete;
AudioRecording(AudioRecording&&) = delete;
AudioRecording& operator=(const AudioRecording&) = delete;
AudioRecording& operator=(AudioRecording&&) = delete;
~AudioRecording();
void update();
void init();
void start();
void stop();
bool is_recording() const;
private:
AudioEngine& m_engine;
ALCdevice* m_capture = nullptr;
bool m_recording = false;
void send_voice(const std::array<int16_t, FRAME_SAMPLES>& pcm);
};
} // namespace Cubed

View File

@@ -5,6 +5,7 @@
#include <AL/al.h>
#include <glm/glm.hpp>
#include <memory>
namespace Cubed {
enum class AudioState { INITIAL, PLAYING, PAUSED, STOPPED };
@@ -21,8 +22,9 @@ public:
void set_pitch(float pitch);
void play();
void play_2d(const AudioBuffer& buffer);
void play_2d(std::unique_ptr<AudioBuffer> buffer);
void play_3d(const AudioBuffer& buffer, const glm::vec3& pos);
void play_3d(std::unique_ptr<AudioBuffer> buffer, const glm::vec3& pos);
void stop();
void pause();
float duration() const;
@@ -42,6 +44,8 @@ public:
void clear_effect_slot();
private:
std::unique_ptr<AudioBuffer> m_buffer;
ALuint m_source = 0;
float m_target_volume = 1.0f;
float m_duration = 0.0f;

View File

@@ -0,0 +1,46 @@
#pragma once
#include "Cubed/audio/audio_effect_slot.hpp"
#include "Cubed/audio/audio_filter.hpp"
#include "glm/ext/vector_float3.hpp"
#include <al.h>
#include <array>
#include <cstdint>
#include <span>
#include <vector>
namespace Cubed {
class AudioStreamSource {
public:
static constexpr int NUM_BUFFERS = 4;
AudioStreamSource();
AudioStreamSource(const AudioStreamSource&) = delete;
AudioStreamSource(AudioStreamSource&&) = delete;
AudioStreamSource& operator=(const AudioStreamSource&) = delete;
AudioStreamSource& operator=(AudioStreamSource&&) = delete;
~AudioStreamSource();
void push_pcm(std::span<const int16_t> pcm, ALsizei sample_rate);
void stop();
bool is_playing() const;
void reset();
void set_volume(float volume);
void set_pitch(float pitch);
void set_pos(glm::vec3 pos);
void set_filter(const AudioFilter& filter);
void clear_filter();
void set_effect_slot(const AudioEffectSlot& slot);
void clear_effect_slot();
private:
ALuint m_source = 0;
std::array<ALuint, NUM_BUFFERS> m_buffers{};
std::vector<ALuint> m_free_buffers;
bool m_playing = false;
void unqueue_processed();
};
} // namespace Cubed

View File

@@ -4,7 +4,7 @@
namespace Cubed {
class SourcePool {
private:
std::vector<AudioSource> m_sources;
std::vector<std::unique_ptr<AudioSource>> m_sources;
public:
explicit SourcePool(size_t size);
@@ -15,9 +15,10 @@ public:
SourcePool& operator=(SourcePool&&) = delete;
void update();
[[nodiscard]]
AudioSource* acquire();
std::vector<AudioSource>& sources();
std::vector<std::unique_ptr<AudioSource>>& sources();
};
} // namespace Cubed

View File

@@ -1,5 +1,4 @@
#pragma once
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/toml.utils.hpp"
namespace Cubed {
@@ -20,7 +19,9 @@ public:
template <TOML::TomlValueType T>
T get(std::string_view key, T default_value) {
ASSERT(m_init);
if (!m_init) {
load_config();
}
if (auto* node = find_node(m_tbl, key)) {
if (auto value = node->value<T>())
return *value;
@@ -32,7 +33,9 @@ public:
}
template <TOML::TomlValueType T> void set(std::string_view key, T&& value) {
ASSERT(m_init);
if (!m_init) {
load_config();
}
auto pos = key.rfind('.');
toml::table* table;
@@ -54,6 +57,14 @@ public:
save_to_file();
}
std::string get(std::string_view key, const char* default_value) {
return get(key, std::string(default_value));
}
void set(std::string_view key, const char* val) {
set(key, std::string(val));
}
private:
toml::table m_tbl;
bool m_init = false;

View File

@@ -0,0 +1,15 @@
#pragma once
#include "Cubed/ui/color.hpp"
#include <cstdint>
#include <string>
namespace Cubed {
struct ChatMessage {
std::string player;
std::string text;
Color color;
bool system_msg = false;
uint64_t time = 0;
};
} // namespace Cubed

View File

@@ -2,6 +2,7 @@
#include "Cubed/audio/audio_engine.hpp"
#include "Cubed/config.hpp"
#include "Cubed/gameplay/block.hpp"
#include "Cubed/gameplay/chat_message.hpp"
#include "Cubed/gameplay/chunk_pos.hpp"
#include "Cubed/gameplay/client_chunk.hpp"
#include "Cubed/gameplay/client_player.hpp"
@@ -78,6 +79,7 @@ public:
void rendering_distance(int rendering_distance);
int get_chunk_task_id() const;
void start_client_thread(std::string_view uuid);
void receive_login_rsp(LoginRsp& rsp);
void stop_client_thread();
void start_thread_pool();
@@ -99,9 +101,15 @@ public:
int chunk_size() const;
static AABB get_block_aabb(const glm::ivec3& pos);
AudioEngine& get_audio();
const AudioEngine& get_audio() const;
Config& get_config();
WorldScene& world_scene();
void set_direct_exit();
void receive_chat_message(ChatMsg& msg);
void send_chat_message(ChatMessage& message);
void receive_voice_message(VoiceMsg& msg);
bool enable_voice_chat() const;
template <typename Fn>
void register_ticktimer(std::string_view id, TickType threshold, Fn&& f) {
m_ticktimers.emplace(
@@ -110,6 +118,11 @@ public:
}
private:
struct VoiceMessage {
std::string data;
glm::vec3 pos;
};
std::atomic<bool> m_is_pending_delete_queue_free{false};
std::mutex m_delete_vbo_mutex;
std::mutex m_delete_vao_mutex;
@@ -147,6 +160,8 @@ private:
tbb::concurrent_queue<std::unique_ptr<ClientChunk>> m_pending_upload_queue;
tbb::concurrent_queue<ChunkPos> m_dirty_chunk_queue;
tbb::concurrent_queue<PendingSound> m_pending_sound;
tbb::concurrent_queue<ChatMessage> m_message_queue;
tbb::concurrent_queue<VoiceMessage> m_voice_queue;
std::deque<ChunkPos> m_dirty_queue;
std::vector<const ChunkRenderSnapshot*> m_render_snapshots;
@@ -163,6 +178,7 @@ private:
std::atomic<bool> m_requesting_chunk{false};
std::atomic<bool> m_is_rebuilding{false};
std::atomic<int> m_chunk_task_id{0};
std::atomic<bool> m_voice_chat{true};
std::shared_ptr<NetworkClient> m_client;
ChunkLoadStyle m_chunk_load_style{ChunkLoadStyle::CENTER};

View File

@@ -21,6 +21,7 @@ public:
bool is_connect_error() const;
std::string get_error_string() const;
void clear_error();
ClientWorld& world();
private:
struct Task {

View File

@@ -61,6 +61,8 @@ enum class PacketEnum : uint16_t {
BLOCK_CHANGE_RSP = 3004,
S2C_CLEAR_ALL_CHUNKS = 3005,
UPDATE_TIME = 3006,
CHAT_MSG = 4001,
VOICE_MSG = 4002,
PING = 9001,
PONG = 9002
@@ -121,6 +123,12 @@ template <> constexpr uint16_t get_packet_id<Pong>() {
template <> constexpr uint16_t get_packet_id<PlayerWaterSound>() {
return std::to_underlying(PacketEnum::PLAYER_WATER_SOUND);
}
template <> constexpr uint16_t get_packet_id<ChatMsg>() {
return std::to_underlying(PacketEnum::CHAT_MSG);
}
template <> constexpr uint16_t get_packet_id<VoiceMsg>() {
return std::to_underlying(PacketEnum::VOICE_MSG);
}
template <typename T>
requires std::derived_from<T, google::protobuf::Message>

View File

@@ -10,7 +10,9 @@
#include "Cubed/gameplay/server_player.hpp"
#include "Cubed/tools/priority_thread_pool.hpp"
#include "Cubed/tools/recent_queue.hpp"
#include "Cubed/tools/sensitive_filter.hpp"
#include "Cubed/tools/thread_pool.hpp"
#include "Cubed/ui/color.hpp"
#include "world/block_change.pb.h"
#include <absl/container/flat_hash_set.h>
@@ -80,6 +82,8 @@ public:
void handle_chunk_req(int task_id, const std::string& uuid, ChunkPos pos);
void handle_block_change(const BlockChangeReq& req);
void handle_chat_message(ChatMsg& msg);
void handle_voice_message(VoiceMsg& msg);
int chunk_size() const;
template <typename Fn>
void register_timer(std::string_view id, TickType threshold, Fn&& f) {
@@ -128,6 +132,9 @@ private:
CaveCarver m_cave_carcer;
RiverWorm m_river_worm;
std::atomic<bool> m_enable_filter{false};
std::atomic<bool> m_voice_chat{true};
SensitiveFilter m_filter;
std::jthread m_gen_thread;
std::jthread m_server_thread;
@@ -189,5 +196,8 @@ private:
std::atomic<std::shared_ptr<PriorityThreadPool>>& thread_pool,
int threads);
void send_server_stop();
void boardcast_message(const std::string& name, const std::string& message,
Color color = Color::WHITE, bool system_msg = false);
};
} // namespace Cubed

View File

@@ -8,6 +8,7 @@ struct SliderVariable {
float mouse_sensitivity = 0.15f;
float sfx = 1.0f;
float music = 0.5f;
float player_voice = 1.0f;
int rendering_distance = 24;
};

View File

@@ -9,6 +9,7 @@
#include "Cubed/ui/pasue_menu_ui_manager.hpp"
#include "Cubed/ui/world_ui_manager.hpp"
namespace Cubed {
enum class VoiceInputType { OFF, PTT, ALWAYS };
class SceneManager;
class WorldScene : public Scene {
public:
@@ -33,14 +34,14 @@ public:
bool pause() const;
void set_pause(bool pause);
void set_error(std::string_view error);
void set_mouse(bool pause);
void set_chatting(bool chatting, bool send);
// Not thread safe
void handle_chat_message(ChatMessage& message);
bool is_recording() const;
private:
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
bool handle_window_resize_event(const WindowResizeEvent& e) override;
bool handle_mouse_wheel_event(const MouseWheelEvent& e) override;
bool handle_key_event(const KeyEvent& e) override;
SceneManager& m_scene_manager;
DevPanel m_dev_panel;
Camera m_camera;
@@ -50,9 +51,18 @@ private:
bool m_paused = false;
bool m_show_hud = true;
bool m_show_dev_pannel = true;
bool m_chatting = false;
PauseMenuUIManager m_pasue_menu;
WorldUIManager m_hud_ui;
ErrorUI m_error_ui;
const Argument& m_argument;
VoiceInputType m_input_type;
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
bool handle_window_resize_event(const WindowResizeEvent& e) override;
bool handle_mouse_wheel_event(const MouseWheelEvent& e) override;
bool handle_key_event(const KeyEvent& e) override;
bool handle_text_input_event(const TextInputEvent&) override;
void load_config();
};
} // namespace Cubed

View File

@@ -56,6 +56,7 @@ public:
TextMesh vertices(const std::string& text);
const Texture* text_texture();
static const std::string& font_path();
static float text_width(const std::string& text);
private:
FT_Library m_ft;

View File

@@ -0,0 +1,24 @@
#pragma once
#include <nlohmann/json.hpp>
namespace Cubed {
class SensitiveFilter {
public:
SensitiveFilter();
void load(const nlohmann::json& j);
std::string filter(std::string_view text);
private:
void insert(const std::u32string& world);
void build();
struct Node {
std::unordered_map<char32_t, int> next;
int fail = 0;
size_t length = 0;
bool end = false;
};
std::vector<Node> trie{1};
};
} // namespace Cubed

View File

@@ -1,6 +1,10 @@
#pragma once
#include "Cubed/tools/cubed_assert.hpp"
#include <cstdint>
#include <string>
#include <utf8cpp/utf8.h>
#include <vector>
namespace Cubed {
inline std::string codepoint_to_utf8(uint32_t cp) {
std::string out;
@@ -38,4 +42,28 @@ inline void utf8_pop_back(std::string& str) {
str.erase(i);
}
inline std::vector<std::string> split_utf8(const std::string& str, int size) {
ASSERT(size > 0);
if (!utf8::is_valid(str)) {
return {};
}
std::vector<std::string> blocks;
auto cur = str.begin();
int chat_count = 0;
for (auto it = str.begin(); it != str.end();) {
if (chat_count >= size) {
blocks.emplace_back(cur, it);
cur = it;
chat_count = 0;
}
utf8::next(it, str.end());
++chat_count;
if (it == str.end()) {
blocks.emplace_back(cur, it);
}
}
return blocks;
}
} // namespace Cubed

View File

@@ -0,0 +1,10 @@
#pragma once
#include <SDL3/SDL_timer.h>
#include <cstdint>
namespace Cubed {
namespace Tools {
inline uint64_t get_time_ticks() { return SDL_GetTicks(); }
} // namespace Tools
} // namespace Cubed

View File

@@ -23,8 +23,8 @@ public:
float width() const override;
float height() const override;
Button& set_width(float width);
Button& set_height(float height);
Button& set_width(float width) override;
Button& set_height(float height) override;
Button& set_background_image(const std::string& path,
TextureManager& texture_manager);
Button& set_default_image(TextureManager& texture_manager);
@@ -54,8 +54,6 @@ private:
"texture/ui/button001.png";
std::function<void()> m_clicked;
float m_width = NORMAL_BUTTON_WIDTH;
float m_height = NORMAL_BUTTON_HEIGHT;
float m_scale = DEFAULT_SCALE;
bool m_auto_scale = false;
void on_render(Renderer& renderer) override;

View File

@@ -0,0 +1,56 @@
#pragma once
#include "Cubed/gameplay/chat_message.hpp"
#include "Cubed/ui/text_field.hpp"
#include "Cubed/ui/widget.hpp"
#include <deque>
namespace Cubed {
class ChatBox : public Widget {
public:
ChatBox(Widget* parent);
void add_message(ChatMessage& message);
ChatBox& set_scale(float scale);
ChatBox& set_text_scale(float scale);
// Only the width of TextField can be set; the height is calculated
// dynamically
ChatBox& set_show_lines(int lines);
ChatBox& set_spacing(float spacing);
ChatBox& clear_input();
std::string& get_input_text();
float width() const override;
float height() const override;
float text_label_width() const;
void set_text_field(std::unique_ptr<TextField> text_field);
void set_typing(bool typing, bool finished);
template <typename F> ChatBox& set_on_finish(F&& f) {
m_text_field->set_on_finish(std::forward<F>(f));
return *this;
}
private:
static constexpr int MAX_MESSGAES_SUM = 50;
static constexpr float DISAPPEAR_TIME = 5.0f;
struct Line {
std::unique_ptr<Label> label;
uint64_t time;
bool render = true;
};
int m_lines = 10;
bool m_scale = 1.0f;
float m_spacing = 0.0f;
float m_text_scale = 1.0f;
float m_text_width = 500.0f;
std::deque<Line> m_messages;
std::unique_ptr<TextField> m_text_field;
void layout();
void on_update(float dt) override;
void on_render(Renderer& renderer) override;
bool handle_text_input_event(const TextInputEvent& e) override;
bool handle_key_event(const KeyEvent& e) override;
std::vector<std::string> wrap_message(const std::string& text) const;
};
} // namespace Cubed

View File

@@ -6,7 +6,7 @@
namespace Cubed {
enum class Color {
BLACK,
BLACK = 0,
WHITE,
RED,
GREEN,
@@ -21,6 +21,39 @@ enum class Color {
BROWN
};
inline constexpr Color color_from_int(int i) {
switch (i) {
case std::to_underlying(Color::BLACK):
return Color::BLACK;
case std::to_underlying(Color::WHITE):
return Color::WHITE;
case std::to_underlying(Color::RED):
return Color::RED;
case std::to_underlying(Color::GREEN):
return Color::GREEN;
case std::to_underlying(Color::BLUE):
return Color::BLUE;
case std::to_underlying(Color::YELLOW):
return Color::YELLOW;
case std::to_underlying(Color::CYAN):
return Color::CYAN;
case std::to_underlying(Color::MAGENTA):
return Color::MAGENTA;
case std::to_underlying(Color::GRAY):
return Color::GRAY;
case std::to_underlying(Color::ORANGE):
return Color::ORANGE;
case std::to_underlying(Color::PURPLE):
return Color::PURPLE;
case std::to_underlying(Color::PINK):
return Color::PINK;
case std::to_underlying(Color::BROWN):
return Color::BROWN;
default:
return Color::WHITE;
}
}
inline constexpr glm::vec4 color_value(Color color) {
using glm::vec4;

View File

@@ -26,8 +26,8 @@ public:
private:
int m_spacing = 0;
float m_content_height = 0;
float m_content_width = 0;
float m_content_height = 0.0f;
float m_content_width = 0.0f;
ColumnLayoutAnchor m_layout_anchor = ColumnLayoutAnchor::CENTER;
};
} // namespace Cubed

View File

@@ -0,0 +1,5 @@
#pragma once
namespace Cubed {
static constexpr const char* DEFAULT_TEXT_FIELD_IMAGE =
"texture/ui/textfield001.png";
}

View File

@@ -21,17 +21,9 @@ public:
Image& set_scale(float scale);
float scale() const;
Image& set_height(float height);
Image& set_width(float width);
Image& set_fill(bool fill);
private:
void on_render(Renderer& renderer) override;
void on_update(float dt) override;
float m_width = 0.0f;
float m_height = 0.0f;
bool m_fill = false;
const Texture* m_texture = nullptr;
glm::vec2 m_pos{0.0f, 0.0f};

View File

@@ -14,10 +14,11 @@ public:
virtual ~Label() = default;
Label& set_text(std::string_view text);
Label& set_color(Color color);
Label& set_scale(float scale);
Label& set_background(std::unique_ptr<Widget> background);
Widget* get_background();
const UIVertexData& data() const;
const TextStyle& text_style() const;
@@ -38,6 +39,7 @@ protected:
private:
TextStyle m_text;
UIVertexData m_data;
std::unique_ptr<Widget> m_background;
float m_real_width = 0.0f;
float m_real_height = 0.0f;
float m_offset_x = 0.0f;

View File

@@ -16,11 +16,6 @@ public:
float height() const override;
float alpha() const;
Rect& set_width(float width);
Rect& set_height(float height);
Rect& set_fill(bool fill);
Rect& set_scale(float scale);
Rect& set_color(Color color);
Rect& set_alpha(float alpha);
@@ -32,10 +27,7 @@ private:
void on_render(Renderer& renderer) override;
Color m_color = Color::WHITE;
float m_width = 0.0f;
float m_height = 0.0f;
float m_scale = 1.0f;
float m_alpha = 1.0f;
bool m_fill = false;
};
} // namespace Cubed

View File

@@ -21,8 +21,8 @@ public:
float height() const override;
Slider& set_scale(float scale);
Slider& set_width(float width);
Slider& set_height(float h);
Slider& set_width(float width) override;
Slider& set_height(float h) override;
Slider& set_slider_text(const std::string& key,
const std::string& variable);
Slider& set_track_image(const std::string& path,
@@ -48,8 +48,7 @@ private:
std::unique_ptr<Label> m_label;
ValueType m_type = ValueType::FLOAT;
float m_scale = DEFAULT_SCALE;
float m_width = NORMAL_SLIDER_WIDTH;
float m_height = NORMAL_SLIDER_HEIGHT;
float m_xpos = 0.0f;
bool m_dragging = false;
bool m_inside = false;

View File

@@ -1,6 +1,5 @@
#pragma once
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/rect.hpp"
#include "Cubed/ui/widget.hpp"
@@ -19,21 +18,22 @@ public:
float width() const override;
float height() const override;
TextField& set_width(float width);
TextField& set_height(float height);
TextField& set_width(float width) override;
TextField& set_height(float height) override;
TextField& set_show_text(const std::string& text);
TextField& set_background_image(const std::string& path,
TextureManager& texture_manager);
TextField& set_default_image(TextureManager& texture_manager);
TextField& set_background(std::unique_ptr<Widget> background);
TextField& set_auto_scale(bool auto_scale);
TextField& set_app(App* app);
TextField& set_typing(bool typing, bool finished);
TextField& clear_input();
bool is_typing() const;
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
bool handle_text_input_event(const TextInputEvent& e) override;
bool handle_key_event(const KeyEvent& e) override;
bool handle_window_resize_event(const WindowResizeEvent& e) override;
const std::string& input_text() const;
std::string& input_text();
template <typename F> TextField& set_on_finish(F&& f) {
m_on_finished = std::forward<F>(f);
return *this;
@@ -44,11 +44,9 @@ private:
static constexpr float DEFAULT_SCALE = 3.0f;
static constexpr float TEXT_SCALE = 0.6f;
static constexpr float CURSOR_INTERVAL = 0.5f;
static constexpr const char* DEFAULT_TEXT_FIELD_IMAGE =
"texture/ui/textfield001.png";
App* m_app = nullptr;
std::unique_ptr<Image> m_background;
std::unique_ptr<Widget> m_background;
std::unique_ptr<Label> m_foreground;
std::unique_ptr<Rect> m_cursor;
float m_cursor_timer = 0.0f;
@@ -57,8 +55,7 @@ private:
bool m_typing = false;
bool m_auto_scale = false;
bool m_ctrl_press = false;
float m_width = NORMAL_TEXTFIELD_WIDTH;
float m_height = NORMAL_TEXTFIELD_HEIGHT;
float m_scale = DEFAULT_SCALE;
std::string m_input_text;
@@ -70,5 +67,8 @@ private:
void on_update(float dt) override;
void update_show_text();
void update_input_area();
void start_typing();
void stop_typing(bool finished);
};
} // namespace Cubed

View File

@@ -34,8 +34,16 @@ public:
virtual Widget& set_window_size(int width, int height);
virtual Widget& set_visible(bool visible);
// Returns the final display size
virtual float width() const = 0;
virtual float height() const = 0;
virtual float width() const;
virtual float height() const;
virtual Widget& set_width(float width);
virtual Widget& set_height(float height);
virtual Widget& set_fill_parent(bool fill);
virtual Widget& set_fill_width(bool fill);
virtual Widget& set_fill_height(bool fill);
virtual glm::vec2 pos() const;
virtual bool handle_key_event(const KeyEvent& e);
@@ -44,7 +52,6 @@ public:
virtual bool handle_window_resize_event(const WindowResizeEvent& e);
virtual bool handle_mouse_move_event(const MouseMoveEvent& e);
virtual bool handle_text_input_event(const TextInputEvent& e);
void set_order(TraversalOrder order);
template <typename T, typename... Args> T& add_child(Args&&... args) {
@@ -56,12 +63,16 @@ public:
protected:
Widget* m_parent = nullptr;
float m_window_height = 0;
float m_window_width = 0;
float m_window_height = 0.0f;
float m_window_width = 0.0f;
float m_width = 0.0f;
float m_height = 0.0f;
// Center is at the top-left corner, position is at the top-left corner
Anchor m_anchor = Anchor::TOP_LEFT;
bool m_visible = true;
bool m_fill_parent = false;
bool m_fill_height = false;
bool m_fill_width = false;
glm::ivec2 m_offset{0, 0};
std::vector<std::unique_ptr<Widget>>& children();

View File

@@ -1,5 +1,7 @@
#pragma once
#include "Cubed/ui/chat_box.hpp"
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/ui_manager.hpp"
#include "Cubed/ui/widget.hpp"
@@ -17,8 +19,17 @@ public:
void init() override;
void render(Renderer& renderer) override;
void update(float dt) override;
void set_chatting(bool chantting, bool sned);
void add_chat_message(ChatMessage& message);
private:
bool handle_key_event(const KeyEvent& e) override;
WorldScene& m_scene;
ChatBox* m_chat_box = nullptr;
Image* m_mircophone = nullptr;
Label* m_disbable_voice = nullptr;
};
} // namespace Cubed

View File

@@ -0,0 +1,2 @@
DisableFormat: true
SortIncludes: false

46
include/utf8cpp/utf8.h Normal file
View File

@@ -0,0 +1,46 @@
// Copyright 2006 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731
#define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731
/*
To control the C++ language version used by the library, you can define UTF_CPP_CPLUSPLUS macro
and set it to one of the values used by the __cplusplus predefined macro.
For instance,
#define UTF_CPP_CPLUSPLUS 199711L
will cause the UTF-8 CPP library to use only types and language features available in the C++ 98 standard.
Some library features will be disabled.
If you leave UTF_CPP_CPLUSPLUS undefined, it will be internally assigned to __cplusplus.
*/
#include "utf8/checked.h"
#include "utf8/unchecked.h"
#endif // header guard

View File

@@ -0,0 +1,359 @@
// Copyright 2006-2016 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#include "core.h"
#include <stdexcept>
namespace utf8
{
// Base for the exceptions that may be thrown from the library
class exception : public ::std::exception {
};
// Exceptions that may be thrown from the library functions.
class invalid_code_point : public exception {
utfchar32_t cp;
public:
invalid_code_point(utfchar32_t codepoint) : cp(codepoint) {}
virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Invalid code point"; }
utfchar32_t code_point() const {return cp;}
};
class invalid_utf8 : public exception {
utfchar8_t u8;
public:
invalid_utf8 (utfchar8_t u) : u8(u) {}
invalid_utf8 (char c) : u8(static_cast<utfchar8_t>(c)) {}
virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Invalid UTF-8"; }
utfchar8_t utf8_octet() const {return u8;}
};
class invalid_utf16 : public exception {
utfchar16_t u16;
public:
invalid_utf16 (utfchar16_t u) : u16(u) {}
virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Invalid UTF-16"; }
utfchar16_t utf16_word() const {return u16;}
};
class not_enough_room : public exception {
public:
virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Not enough space"; }
};
/// The library API - functions intended to be called by the users
template <typename octet_iterator>
octet_iterator append(utfchar32_t cp, octet_iterator result)
{
if (!utf8::internal::is_code_point_valid(cp))
throw invalid_code_point(cp);
return internal::append(cp, result);
}
inline void append(utfchar32_t cp, std::string& s)
{
append(cp, std::back_inserter(s));
}
template <typename word_iterator>
word_iterator append16(utfchar32_t cp, word_iterator result)
{
if (!utf8::internal::is_code_point_valid(cp))
throw invalid_code_point(cp);
return internal::append16(cp, result);
}
template <typename octet_iterator, typename output_iterator>
output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, utfchar32_t replacement)
{
while (start != end) {
octet_iterator sequence_start = start;
internal::utf_error err_code = utf8::internal::validate_next(start, end);
switch (err_code) {
case internal::UTF8_OK :
for (octet_iterator it = sequence_start; it != start; ++it)
*out++ = *it;
break;
case internal::NOT_ENOUGH_ROOM:
out = utf8::append (replacement, out);
start = end;
break;
case internal::INVALID_LEAD:
out = utf8::append (replacement, out);
++start;
break;
case internal::INCOMPLETE_SEQUENCE:
case internal::OVERLONG_SEQUENCE:
case internal::INVALID_CODE_POINT:
out = utf8::append (replacement, out);
++start;
// just one replacement mark for the sequence
while (start != end && utf8::internal::is_trail(*start))
++start;
break;
}
}
return out;
}
template <typename octet_iterator, typename output_iterator>
inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out)
{
static const utfchar32_t replacement_marker = static_cast<utfchar32_t>(utf8::internal::mask16(0xfffd));
return utf8::replace_invalid(start, end, out, replacement_marker);
}
inline std::string replace_invalid(const std::string& s, utfchar32_t replacement)
{
std::string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement);
return result;
}
inline std::string replace_invalid(const std::string& s)
{
std::string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result));
return result;
}
template <typename octet_iterator>
utfchar32_t next(octet_iterator& it, octet_iterator end)
{
utfchar32_t cp = 0;
internal::utf_error err_code = utf8::internal::validate_next(it, end, cp);
switch (err_code) {
case internal::UTF8_OK :
break;
case internal::NOT_ENOUGH_ROOM :
throw not_enough_room();
case internal::INVALID_LEAD :
case internal::INCOMPLETE_SEQUENCE :
case internal::OVERLONG_SEQUENCE :
throw invalid_utf8(static_cast<utfchar8_t>(*it));
case internal::INVALID_CODE_POINT :
throw invalid_code_point(cp);
}
return cp;
}
template <typename word_iterator>
utfchar32_t next16(word_iterator& it, word_iterator end)
{
utfchar32_t cp = 0;
internal::utf_error err_code = utf8::internal::validate_next16(it, end, cp);
if (err_code == internal::NOT_ENOUGH_ROOM)
throw not_enough_room();
return cp;
}
template <typename octet_iterator>
utfchar32_t peek_next(octet_iterator it, octet_iterator end)
{
return utf8::next(it, end);
}
template <typename octet_iterator>
utfchar32_t prior(octet_iterator& it, octet_iterator start)
{
// can't do much if it == start
if (it == start)
throw not_enough_room();
octet_iterator end = it;
// Go back until we hit either a lead octet or start
while (utf8::internal::is_trail(*(--it)))
if (it == start)
throw invalid_utf8(*it); // error - no lead byte in the sequence
return utf8::peek_next(it, end);
}
template <typename octet_iterator, typename distance_type>
void advance (octet_iterator& it, distance_type n, octet_iterator end)
{
const distance_type zero(0);
if (n < zero) {
// backward
for (distance_type i = n; i < zero; ++i)
utf8::prior(it, end);
} else {
// forward
for (distance_type i = zero; i < n; ++i)
utf8::next(it, end);
}
}
template <typename octet_iterator>
typename std::iterator_traits<octet_iterator>::difference_type
distance (octet_iterator first, octet_iterator last)
{
typename std::iterator_traits<octet_iterator>::difference_type dist;
for (dist = 0; first < last; ++dist)
utf8::next(first, last);
return dist;
}
template <typename u16bit_iterator, typename octet_iterator>
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result)
{
while (start != end) {
utfchar32_t cp = static_cast<utfchar32_t>(utf8::internal::mask16(*start++));
// Take care of surrogate pairs first
if (utf8::internal::is_lead_surrogate(cp)) {
if (start != end) {
const utfchar32_t trail_surrogate = static_cast<utfchar32_t>(utf8::internal::mask16(*start++));
if (utf8::internal::is_trail_surrogate(trail_surrogate))
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET;
else
throw invalid_utf16(static_cast<utfchar16_t>(trail_surrogate));
}
else
throw invalid_utf16(static_cast<utfchar16_t>(cp));
}
// Lone trail surrogate
else if (utf8::internal::is_trail_surrogate(cp))
throw invalid_utf16(static_cast<utfchar16_t>(cp));
result = utf8::append(cp, result);
}
return result;
}
template <typename u16bit_iterator, typename octet_iterator>
u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result)
{
while (start < end) {
const utfchar32_t cp = utf8::next(start, end);
if (cp > 0xffff) { //make a surrogate pair
*result++ = static_cast<utfchar16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<utfchar16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
}
else
*result++ = static_cast<utfchar16_t>(cp);
}
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result)
{
while (start != end)
result = utf8::append(*(start++), result);
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result)
{
while (start < end)
(*result++) = utf8::next(start, end);
return result;
}
// The iterator class
template <typename octet_iterator>
class iterator {
octet_iterator it;
octet_iterator range_start;
octet_iterator range_end;
public:
typedef utfchar32_t value_type;
typedef utfchar32_t* pointer;
typedef utfchar32_t& reference;
typedef std::ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
iterator () {}
explicit iterator (const octet_iterator& octet_it,
const octet_iterator& rangestart,
const octet_iterator& rangeend) :
it(octet_it), range_start(rangestart), range_end(rangeend)
{
if (it < range_start || it > range_end)
throw std::out_of_range("Invalid utf-8 iterator position");
}
// the default "big three" are OK
octet_iterator base () const { return it; }
utfchar32_t operator * () const
{
octet_iterator temp = it;
return utf8::next(temp, range_end);
}
bool operator == (const iterator& rhs) const
{
if (range_start != rhs.range_start || range_end != rhs.range_end)
throw std::logic_error("Comparing utf-8 iterators defined with different ranges");
return (it == rhs.it);
}
bool operator != (const iterator& rhs) const
{
return !(operator == (rhs));
}
iterator& operator ++ ()
{
utf8::next(it, range_end);
return *this;
}
iterator operator ++ (int)
{
iterator temp = *this;
utf8::next(it, range_end);
return temp;
}
iterator& operator -- ()
{
utf8::prior(it, range_start);
return *this;
}
iterator operator -- (int)
{
iterator temp = *this;
utf8::prior(it, range_start);
return temp;
}
}; // class iterator
} // namespace utf8
#if UTF_CPP_CPLUSPLUS >= 202002L // C++ 20 or later
#include "cpp20.h"
#elif UTF_CPP_CPLUSPLUS >= 201703L // C++ 17 or later
#include "cpp17.h"
#elif UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later
#include "cpp11.h"
#endif // C++ 11 or later
#endif //header guard

610
include/utf8cpp/utf8/core.h Normal file
View File

@@ -0,0 +1,610 @@
// Copyright 2006 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#define UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#include <iterator>
#include <cstring>
#include <string>
// Determine the C++ standard version.
// If the user defines UTF_CPP_CPLUSPLUS, use that.
// Otherwise, trust the unreliable predefined macro __cplusplus
#if !defined UTF_CPP_CPLUSPLUS
#define UTF_CPP_CPLUSPLUS __cplusplus
#endif
#if UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later
#define UTF_CPP_OVERRIDE override
#define UTF_CPP_NOEXCEPT noexcept
#define UTF_CPP_STATIC_ASSERT(condition) static_assert(condition, "UTFCPP static assert");
#else // C++ 98/03
#define UTF_CPP_OVERRIDE
#define UTF_CPP_NOEXCEPT throw()
// Not worth simulating static_assert:
#define UTF_CPP_STATIC_ASSERT(condition) (void)(condition);
#endif // C++ 11 or later
namespace utf8
{
// The typedefs for 8-bit, 16-bit and 32-bit code units
#if UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later
#if UTF_CPP_CPLUSPLUS >= 202002L // C++ 20 or later
typedef char8_t utfchar8_t;
#else // C++ 11/14/17
typedef unsigned char utfchar8_t;
#endif
typedef char16_t utfchar16_t;
typedef char32_t utfchar32_t;
#else // C++ 98/03
typedef unsigned char utfchar8_t;
typedef unsigned short utfchar16_t;
typedef unsigned int utfchar32_t;
#endif // C++ 11 or later
// Helper code - not intended to be directly called by the library users. May be changed at any time
namespace internal
{
// Unicode constants
// Leading (high) surrogates: 0xd800 - 0xdbff
// Trailing (low) surrogates: 0xdc00 - 0xdfff
const utfchar16_t LEAD_SURROGATE_MIN = 0xd800u;
const utfchar16_t LEAD_SURROGATE_MAX = 0xdbffu;
const utfchar16_t TRAIL_SURROGATE_MIN = 0xdc00u;
const utfchar16_t TRAIL_SURROGATE_MAX = 0xdfffu;
const utfchar16_t LEAD_OFFSET = 0xd7c0u; // LEAD_SURROGATE_MIN - (0x10000 >> 10)
const utfchar32_t SURROGATE_OFFSET = 0xfca02400u; // 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN
// Maximum valid value for a Unicode code point
const utfchar32_t CODE_POINT_MAX = 0x0010ffffu;
template<typename octet_type>
inline utfchar8_t mask8(octet_type oc)
{
return static_cast<utfchar8_t>(0xff & oc);
}
template<typename u16_type>
inline utfchar16_t mask16(u16_type oc)
{
return static_cast<utfchar16_t>(0xffff & oc);
}
template<typename octet_type>
inline bool is_trail(octet_type oc)
{
return ((utf8::internal::mask8(oc) >> 6) == 0x2);
}
inline bool is_lead_surrogate(utfchar32_t cp)
{
return (cp >= static_cast<utfchar32_t>(LEAD_SURROGATE_MIN) && cp <= static_cast<utfchar32_t>(LEAD_SURROGATE_MAX));
}
inline bool is_trail_surrogate(utfchar32_t cp)
{
return (cp >= static_cast<utfchar32_t>(TRAIL_SURROGATE_MIN) && cp <= static_cast<utfchar32_t>(TRAIL_SURROGATE_MAX));
}
inline bool is_surrogate(utfchar32_t cp)
{
return (cp >= static_cast<utfchar32_t>(LEAD_SURROGATE_MIN) && cp <= static_cast<utfchar32_t>(TRAIL_SURROGATE_MAX));
}
inline bool is_code_point_valid(utfchar32_t cp)
{
return (cp <= CODE_POINT_MAX && !utf8::internal::is_surrogate(cp));
}
inline bool is_in_bmp(utfchar32_t cp)
{
return cp < utfchar32_t(0x10000);
}
template <typename octet_iterator>
int sequence_length(octet_iterator lead_it)
{
const utfchar8_t lead = utf8::internal::mask8(*lead_it);
if (lead < 0x80)
return 1;
else if ((lead >> 5) == 0x6)
return 2;
else if ((lead >> 4) == 0xe)
return 3;
else if ((lead >> 3) == 0x1e)
return 4;
else
return 0;
}
inline bool is_overlong_sequence(utfchar32_t cp, int length)
{
if (cp < 0x80) {
if (length != 1)
return true;
}
else if (cp < 0x800) {
if (length != 2)
return true;
}
else if (cp < 0x10000) {
if (length != 3)
return true;
}
return false;
}
enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT};
/// Helper for get_sequence_x
template <typename octet_iterator>
utf_error increase_safely(octet_iterator& it, const octet_iterator end)
{
if (++it == end)
return NOT_ENOUGH_ROOM;
if (!utf8::internal::is_trail(*it))
return INCOMPLETE_SEQUENCE;
return UTF8_OK;
}
#define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;}
/// get_sequence_x functions decode utf-8 sequences of the length x
template <typename octet_iterator>
utf_error get_sequence_1(octet_iterator& it, octet_iterator end, utfchar32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = static_cast<utfchar32_t>(utf8::internal::mask8(*it));
return UTF8_OK;
}
template <typename octet_iterator>
utf_error get_sequence_2(octet_iterator& it, octet_iterator end, utfchar32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = static_cast<utfchar32_t>(utf8::internal::mask8(*it));
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
code_point = ((code_point << 6) & 0x7ff) + ((*it) & 0x3f);
return UTF8_OK;
}
template <typename octet_iterator>
utf_error get_sequence_3(octet_iterator& it, octet_iterator end, utfchar32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = static_cast<utfchar32_t>(utf8::internal::mask8(*it));
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
code_point = ((code_point << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff);
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
code_point = static_cast<utfchar32_t>(code_point + ((*it) & 0x3f));
return UTF8_OK;
}
template <typename octet_iterator>
utf_error get_sequence_4(octet_iterator& it, octet_iterator end, utfchar32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
code_point = static_cast<utfchar32_t>(utf8::internal::mask8(*it));
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
code_point = ((code_point << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff);
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
code_point = static_cast<utfchar32_t>(code_point + ((utf8::internal::mask8(*it) << 6) & 0xfff));
UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end)
code_point = static_cast<utfchar32_t>(code_point + ((*it) & 0x3f));
return UTF8_OK;
}
#undef UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR
template <typename octet_iterator>
utf_error validate_next(octet_iterator& it, octet_iterator end, utfchar32_t& code_point)
{
if (it == end)
return NOT_ENOUGH_ROOM;
// Save the original value of it so we can go back in case of failure
// Of course, it does not make much sense with i.e. stream iterators
octet_iterator original_it = it;
utfchar32_t cp = 0;
// Determine the sequence length based on the lead octet
const int length = utf8::internal::sequence_length(it);
// Get trail octets and calculate the code point
utf_error err = UTF8_OK;
switch (length) {
case 0:
return INVALID_LEAD;
case 1:
err = utf8::internal::get_sequence_1(it, end, cp);
// No need for further validations
if (err == UTF8_OK) {
code_point = cp;
++it;
return UTF8_OK;
} else {
it = original_it;
return err;
}
break; // just to make sure there are no warnings
case 2:
err = utf8::internal::get_sequence_2(it, end, cp);
break;
case 3:
err = utf8::internal::get_sequence_3(it, end, cp);
break;
case 4:
err = utf8::internal::get_sequence_4(it, end, cp);
break;
}
if (err == UTF8_OK) {
// Decoding succeeded. Now, security checks...
if (utf8::internal::is_code_point_valid(cp)) {
if (!utf8::internal::is_overlong_sequence(cp, length)){
// Passed! Return here.
code_point = cp;
++it;
return UTF8_OK;
}
else
err = OVERLONG_SEQUENCE;
}
else
err = INVALID_CODE_POINT;
}
// Failure branch - restore the original value of the iterator
it = original_it;
return err;
}
template <typename octet_iterator>
inline utf_error validate_next(octet_iterator& it, octet_iterator end) {
if (it == end)
return NOT_ENOUGH_ROOM;
octet_iterator original_it = it;
const utfchar8_t lead = utf8::internal::mask8(*it);
if (lead < 0x80) {
++it;
return UTF8_OK;
} else if ((lead & 0xE0) == 0xC0) {
// two-byte sequence
if (lead == 0xC0 || lead == 0xC1) {
it = original_it;
return OVERLONG_SEQUENCE;
}
if (++it == end) {
it = original_it;
return NOT_ENOUGH_ROOM;
}
const utfchar8_t trail1 = utf8::internal::mask8(*it);
if ((trail1 & 0xC0) != 0x80) {
it = original_it;
return INCOMPLETE_SEQUENCE;
}
++it;
return UTF8_OK;
} else if ((lead & 0xF0) == 0xE0) {
// three-byte sequence
if (++it == end) {
it = original_it;
return NOT_ENOUGH_ROOM;
}
const utfchar8_t trail1 = utf8::internal::mask8(*it);
if ((trail1 & 0xC0) != 0x80) {
it = original_it;
return INCOMPLETE_SEQUENCE;
}
if (++it == end) {
it = original_it;
return NOT_ENOUGH_ROOM;
}
const utfchar8_t trail2 = utf8::internal::mask8(*it);
if ((trail2 & 0xC0) != 0x80) {
it = original_it;
return INCOMPLETE_SEQUENCE;
}
if (lead == 0xE0 && trail1 < 0xA0) {
it = original_it;
return OVERLONG_SEQUENCE;
}
if (lead == 0xED && trail1 > 0x9F) {
it = original_it;
return INVALID_CODE_POINT;
}
++it;
return UTF8_OK;
} else if ((lead & 0xF8) == 0xF0) {
// four-byte sequence
if (++it == end) {
it = original_it;
return NOT_ENOUGH_ROOM;
}
const utfchar8_t trail1 = utf8::internal::mask8(*it);
if ((trail1 & 0xC0) != 0x80) {
it = original_it;
return INCOMPLETE_SEQUENCE;
}
if (++it == end) {
it = original_it;
return NOT_ENOUGH_ROOM;
}
const utfchar8_t trail2 = utf8::internal::mask8(*it);
if ((trail2 & 0xC0) != 0x80) {
it = original_it;
return INCOMPLETE_SEQUENCE;
}
if (++it == end) {
it = original_it;
return NOT_ENOUGH_ROOM;
}
const utfchar8_t trail3 = utf8::internal::mask8(*it);
if ((trail3 & 0xC0) != 0x80) {
it = original_it;
return INCOMPLETE_SEQUENCE;
}
if (lead == 0xF0 && trail1 < 0x90) {
it = original_it;
return OVERLONG_SEQUENCE;
}
if (lead == 0xF4 && trail1 > 0x8F) {
it = original_it;
return INVALID_CODE_POINT;
}
if (lead >= 0xF5) {
it = original_it;
return INVALID_CODE_POINT;
}
++it;
return UTF8_OK;
} else {
it = original_it;
return INVALID_LEAD;
}
}
template <typename word_iterator>
utf_error validate_next16(word_iterator& it, word_iterator end, utfchar32_t& code_point)
{
// Make sure the iterator dereferences a large enough type
typedef typename std::iterator_traits<word_iterator>::value_type word_type;
UTF_CPP_STATIC_ASSERT(sizeof(word_type) >= sizeof(utfchar16_t));
// Check the edge case:
if (it == end)
return NOT_ENOUGH_ROOM;
// Save the original value of it so we can go back in case of failure
// Of course, it does not make much sense with i.e. stream iterators
word_iterator original_it = it;
utf_error err = UTF8_OK;
const utfchar16_t first_word = *it++;
if (!is_surrogate(first_word)) {
code_point = first_word;
return UTF8_OK;
}
else {
if (it == end)
err = NOT_ENOUGH_ROOM;
else if (is_lead_surrogate(first_word)) {
const utfchar16_t second_word = *it++;
if (is_trail_surrogate(static_cast<utfchar32_t>(second_word))) {
code_point = static_cast<utfchar32_t>(first_word << 10) + static_cast<utfchar32_t>(second_word) + SURROGATE_OFFSET;
return UTF8_OK;
} else
err = INCOMPLETE_SEQUENCE;
} else {
err = INVALID_LEAD;
}
}
// error branch
it = original_it;
return err;
}
// Internal implementation of both checked and unchecked append() function
// This function will be invoked by the overloads below, as they will know
// the octet_type.
template <typename octet_iterator, typename octet_type>
octet_iterator append(utfchar32_t cp, octet_iterator result) {
if (cp < 0x80) // one octet
*(result++) = static_cast<octet_type>(cp);
else if (cp < 0x800) { // two octets
*(result++) = static_cast<octet_type>((cp >> 6) | 0xc0);
*(result++) = static_cast<octet_type>((cp & 0x3f) | 0x80);
}
else if (cp < 0x10000) { // three octets
*(result++) = static_cast<octet_type>((cp >> 12) | 0xe0);
*(result++) = static_cast<octet_type>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<octet_type>((cp & 0x3f) | 0x80);
}
else { // four octets
*(result++) = static_cast<octet_type>((cp >> 18) | 0xf0);
*(result++) = static_cast<octet_type>(((cp >> 12) & 0x3f)| 0x80);
*(result++) = static_cast<octet_type>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<octet_type>((cp & 0x3f) | 0x80);
}
return result;
}
// One of the following overloads will be invoked from the API calls
// A simple (but dangerous) case: the caller appends byte(s) to a char array
inline char* append(utfchar32_t cp, char* result) {
return append<char*, char>(cp, result);
}
// Hopefully, most common case: the caller uses back_inserter
// i.e. append(cp, std::back_inserter(str));
template<typename container_type>
std::back_insert_iterator<container_type> append
(utfchar32_t cp, std::back_insert_iterator<container_type> result) {
return append<std::back_insert_iterator<container_type>,
typename container_type::value_type>(cp, result);
}
// The caller uses some other kind of output operator - not covered above
// Note that in this case we are not able to determine octet_type
// so we assume it's utfchar8_t; that can cause a conversion warning if we are wrong.
template <typename octet_iterator>
octet_iterator append(utfchar32_t cp, octet_iterator result) {
return append<octet_iterator, utfchar8_t>(cp, result);
}
// Internal implementation of both checked and unchecked append16() function
// This function will be invoked by the overloads below, as they will know
// the word_type.
template <typename word_iterator, typename word_type>
word_iterator append16(utfchar32_t cp, word_iterator result) {
UTF_CPP_STATIC_ASSERT(sizeof(word_type) >= sizeof(utfchar16_t));
if (is_in_bmp(cp))
*(result++) = static_cast<word_type>(cp);
else {
// Code points from the supplementary planes are encoded via surrogate pairs
*(result++) = static_cast<word_type>(LEAD_OFFSET + (cp >> 10));
*(result++) = static_cast<word_type>(TRAIL_SURROGATE_MIN + (cp & 0x3FF));
}
return result;
}
// Hopefully, most common case: the caller uses back_inserter
// i.e. append16(cp, std::back_inserter(str));
template<typename container_type>
std::back_insert_iterator<container_type> append16
(utfchar32_t cp, std::back_insert_iterator<container_type> result) {
return append16<std::back_insert_iterator<container_type>,
typename container_type::value_type>(cp, result);
}
// The caller uses some other kind of output operator - not covered above
// Note that in this case we are not able to determine word_type
// so we assume it's utfchar16_t; that can cause a conversion warning if we are wrong.
template <typename word_iterator>
word_iterator append16(utfchar32_t cp, word_iterator result) {
return append16<word_iterator, utfchar16_t>(cp, result);
}
} // namespace internal
/// The library API - functions intended to be called by the users
// Byte order mark
const utfchar8_t bom[] = {0xef, 0xbb, 0xbf};
template <typename octet_iterator>
octet_iterator find_invalid(octet_iterator start, octet_iterator end)
{
octet_iterator result = start;
while (result != end) {
utf8::internal::utf_error err_code = utf8::internal::validate_next(result, end);
if (err_code != internal::UTF8_OK)
return result;
}
return result;
}
inline const char* find_invalid(const char* str)
{
const char* end = str + std::strlen(str);
return find_invalid(str, end);
}
inline std::size_t find_invalid(const std::string& s)
{
std::string::const_iterator invalid = find_invalid(s.begin(), s.end());
return (invalid == s.end()) ? std::string::npos : static_cast<std::size_t>(invalid - s.begin());
}
template <typename octet_iterator>
inline bool is_valid(octet_iterator start, octet_iterator end)
{
return (utf8::find_invalid(start, end) == end);
}
inline bool is_valid(const char* str)
{
return (*(utf8::find_invalid(str)) == '\0');
}
inline bool is_valid(const std::string& s)
{
return is_valid(s.begin(), s.end());
}
template <typename octet_iterator>
inline bool starts_with_bom (octet_iterator it, octet_iterator end)
{
return (
((it != end) && (utf8::internal::mask8(*it++)) == bom[0]) &&
((it != end) && (utf8::internal::mask8(*it++)) == bom[1]) &&
((it != end) && (utf8::internal::mask8(*it)) == bom[2])
);
}
inline bool starts_with_bom(const std::string& s)
{
return starts_with_bom(s.begin(), s.end());
}
} // namespace utf8
#endif // header guard

View File

@@ -0,0 +1,70 @@
// Copyright 2018 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1
#define UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1
#include "checked.h"
namespace utf8
{
inline void append16(utfchar32_t cp, std::u16string& s)
{
append16(cp, std::back_inserter(s));
}
inline std::string utf16to8(const std::u16string& s)
{
std::string result;
utf16to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u16string utf8to16(const std::string& s)
{
std::u16string result;
utf8to16(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::string utf32to8(const std::u32string& s)
{
std::string result;
utf32to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u32string utf8to32(const std::string& s)
{
std::u32string result;
utf8to32(s.begin(), s.end(), std::back_inserter(result));
return result;
}
} // namespace utf8
#endif // header guard

View File

@@ -0,0 +1,96 @@
// Copyright 2018 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_7e906c01_03a3_4daf_b420_ea7ea952b3c9
#define UTF8_FOR_CPP_7e906c01_03a3_4daf_b420_ea7ea952b3c9
#include "cpp11.h"
namespace utf8
{
inline std::string utf16to8(std::u16string_view s)
{
std::string result;
utf16to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u16string utf8to16(std::string_view s)
{
std::u16string result;
utf8to16(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::string utf32to8(std::u32string_view s)
{
std::string result;
utf32to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u32string utf8to32(std::string_view s)
{
std::u32string result;
utf8to32(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::size_t find_invalid(std::string_view s)
{
std::string_view::const_iterator invalid = find_invalid(s.begin(), s.end());
return (invalid == s.end()) ? std::string_view::npos : static_cast<std::size_t>(invalid - s.begin());
}
inline bool is_valid(std::string_view s)
{
return is_valid(s.begin(), s.end());
}
inline std::string replace_invalid(std::string_view s, char32_t replacement)
{
std::string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement);
return result;
}
inline std::string replace_invalid(std::string_view s)
{
std::string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline bool starts_with_bom(std::string_view s)
{
return starts_with_bom(s.begin(), s.end());
}
} // namespace utf8
#endif // header guard

View File

@@ -0,0 +1,124 @@
// Copyright 2022 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_207e906c01_03a3_4daf_b420_ea7ea952b3c9
#define UTF8_FOR_CPP_207e906c01_03a3_4daf_b420_ea7ea952b3c9
#include "cpp17.h"
namespace utf8
{
inline std::u8string utf16tou8(const std::u16string& s)
{
std::u8string result;
utf16to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u8string utf16tou8(std::u16string_view s)
{
std::u8string result;
utf16to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u16string utf8to16(const std::u8string& s)
{
std::u16string result;
utf8to16(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u16string utf8to16(const std::u8string_view& s)
{
std::u16string result;
utf8to16(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u8string utf32tou8(const std::u32string& s)
{
std::u8string result;
utf32to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u8string utf32tou8(const std::u32string_view& s)
{
std::u8string result;
utf32to8(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u32string utf8to32(const std::u8string& s)
{
std::u32string result;
utf8to32(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::u32string utf8to32(const std::u8string_view& s)
{
std::u32string result;
utf8to32(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline std::size_t find_invalid(const std::u8string& s)
{
std::u8string::const_iterator invalid = find_invalid(s.begin(), s.end());
return (invalid == s.end()) ? std::string_view::npos : static_cast<std::size_t>(invalid - s.begin());
}
inline bool is_valid(const std::u8string& s)
{
return is_valid(s.begin(), s.end());
}
inline std::u8string replace_invalid(const std::u8string& s, char32_t replacement)
{
std::u8string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement);
return result;
}
inline std::u8string replace_invalid(const std::u8string& s)
{
std::u8string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result));
return result;
}
inline bool starts_with_bom(const std::u8string& s)
{
return starts_with_bom(s.begin(), s.end());
}
} // namespace utf8
#endif // header guard

View File

@@ -0,0 +1,286 @@
// Copyright 2006 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#define UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#include "core.h"
namespace utf8
{
namespace unchecked
{
template <typename octet_iterator>
octet_iterator append(utfchar32_t cp, octet_iterator result)
{
return internal::append(cp, result);
}
template <typename word_iterator>
word_iterator append16(utfchar32_t cp, word_iterator result)
{
return internal::append16(cp, result);
}
template <typename octet_iterator, typename output_iterator>
output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, utfchar32_t replacement)
{
while (start != end) {
octet_iterator sequence_start = start;
internal::utf_error err_code = utf8::internal::validate_next(start, end);
switch (err_code) {
case internal::UTF8_OK :
for (octet_iterator it = sequence_start; it != start; ++it)
*out++ = *it;
break;
case internal::NOT_ENOUGH_ROOM:
out = utf8::unchecked::append(replacement, out);
start = end;
break;
case internal::INVALID_LEAD:
out = utf8::unchecked::append(replacement, out);
++start;
break;
case internal::INCOMPLETE_SEQUENCE:
case internal::OVERLONG_SEQUENCE:
case internal::INVALID_CODE_POINT:
out = utf8::unchecked::append(replacement, out);
++start;
// just one replacement mark for the sequence
while (start != end && utf8::internal::is_trail(*start))
++start;
break;
}
}
return out;
}
template <typename octet_iterator, typename output_iterator>
inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out)
{
static const utfchar32_t replacement_marker = static_cast<utfchar32_t>(utf8::internal::mask16(0xfffd));
return utf8::unchecked::replace_invalid(start, end, out, replacement_marker);
}
inline std::string replace_invalid(const std::string& s, utfchar32_t replacement)
{
std::string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement);
return result;
}
inline std::string replace_invalid(const std::string& s)
{
std::string result;
replace_invalid(s.begin(), s.end(), std::back_inserter(result));
return result;
}
template <typename octet_iterator>
utfchar32_t next(octet_iterator& it)
{
utfchar32_t cp = utf8::internal::mask8(*it);
switch (utf8::internal::sequence_length(it)) {
case 1:
break;
case 2:
++it;
cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f);
break;
case 3:
++it;
cp = ((cp << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff);
++it;
cp = static_cast<utfchar32_t>(cp + ((*it) & 0x3f));
break;
case 4:
++it;
cp = ((cp << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff);
++it;
cp = static_cast<utfchar32_t>(cp + ((utf8::internal::mask8(*it) << 6) & 0xfff));
++it;
cp = static_cast<utfchar32_t>(cp + ((*it) & 0x3f));
break;
}
++it;
return cp;
}
template <typename octet_iterator>
utfchar32_t peek_next(octet_iterator it)
{
return utf8::unchecked::next(it);
}
template <typename word_iterator>
utfchar32_t next16(word_iterator& it)
{
utfchar32_t cp = utf8::internal::mask16(*it++);
if (utf8::internal::is_lead_surrogate(cp))
return (cp << 10) + *it++ + utf8::internal::SURROGATE_OFFSET;
return cp;
}
template <typename octet_iterator>
utfchar32_t prior(octet_iterator& it)
{
while (utf8::internal::is_trail(*(--it))) ;
octet_iterator temp = it;
return utf8::unchecked::next(temp);
}
template <typename octet_iterator, typename distance_type>
void advance(octet_iterator& it, distance_type n)
{
const distance_type zero(0);
if (n < zero) {
// backward
for (distance_type i = n; i < zero; ++i)
utf8::unchecked::prior(it);
} else {
// forward
for (distance_type i = zero; i < n; ++i)
utf8::unchecked::next(it);
}
}
template <typename octet_iterator>
typename std::iterator_traits<octet_iterator>::difference_type
distance(octet_iterator first, octet_iterator last)
{
typename std::iterator_traits<octet_iterator>::difference_type dist;
for (dist = 0; first < last; ++dist)
utf8::unchecked::next(first);
return dist;
}
template <typename u16bit_iterator, typename octet_iterator>
octet_iterator utf16to8(u16bit_iterator start, u16bit_iterator end, octet_iterator result)
{
while (start != end) {
utfchar32_t cp = utf8::internal::mask16(*start++);
// Take care of surrogate pairs first
if (utf8::internal::is_lead_surrogate(cp)) {
if (start == end)
return result;
utfchar32_t trail_surrogate = utf8::internal::mask16(*start++);
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET;
}
result = utf8::unchecked::append(cp, result);
}
return result;
}
template <typename u16bit_iterator, typename octet_iterator>
u16bit_iterator utf8to16(octet_iterator start, octet_iterator end, u16bit_iterator result)
{
while (start < end) {
utfchar32_t cp = utf8::unchecked::next(start);
if (cp > 0xffff) { //make a surrogate pair
*result++ = static_cast<utfchar16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<utfchar16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
}
else
*result++ = static_cast<utfchar16_t>(cp);
}
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
octet_iterator utf32to8(u32bit_iterator start, u32bit_iterator end, octet_iterator result)
{
while (start != end)
result = utf8::unchecked::append(*(start++), result);
return result;
}
template <typename octet_iterator, typename u32bit_iterator>
u32bit_iterator utf8to32(octet_iterator start, octet_iterator end, u32bit_iterator result)
{
while (start < end)
(*result++) = utf8::unchecked::next(start);
return result;
}
// The iterator class
template <typename octet_iterator>
class iterator {
octet_iterator it;
public:
typedef utfchar32_t value_type;
typedef utfchar32_t* pointer;
typedef utfchar32_t& reference;
typedef std::ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
iterator () {}
explicit iterator (const octet_iterator& octet_it): it(octet_it) {}
// the default "big three" are OK
octet_iterator base () const { return it; }
utfchar32_t operator * () const
{
octet_iterator temp = it;
return utf8::unchecked::next(temp);
}
bool operator == (const iterator& rhs) const
{
return (it == rhs.it);
}
bool operator != (const iterator& rhs) const
{
return !(operator == (rhs));
}
iterator& operator ++ ()
{
::std::advance(it, utf8::internal::sequence_length(it));
return *this;
}
iterator operator ++ (int)
{
iterator temp = *this;
::std::advance(it, utf8::internal::sequence_length(it));
return temp;
}
iterator& operator -- ()
{
utf8::unchecked::prior(it);
return *this;
}
iterator operator -- (int)
{
iterator temp = *this;
utf8::unchecked::prior(it);
return temp;
}
}; // class iterator
} // namespace utf8::unchecked
} // namespace utf8
#endif // header guard

View File

@@ -85,4 +85,8 @@ target_sources(${PROJECT_NAME}
ui/error_ui.cpp
localization.cpp
tools/system_locate.cpp
ui/chat_box.cpp
audio/audio_recording.cpp
audio/audio_stream_source.cpp
tools/sensitive_filter.cpp
)

View File

@@ -823,11 +823,15 @@ std::string App::get_clipboard_text() {
}
void App::start_text_input() {
Logger::debug("Start Text Input");
if (!SDL_StartTextInput(m_window.get_window())) {
Logger::error("Start Text Input Fail: {}", SDL_GetError());
}
}
void App::stop_text_input() { SDL_StopTextInput(m_window.get_window()); }
void App::stop_text_input() {
Logger::debug("Stop Text Input");
SDL_StopTextInput(m_window.get_window());
}
void App::update_text_input_area(const glm::vec4& textbox,
float cursor_position_x) {

View File

@@ -13,9 +13,7 @@ float AudioBuffer::duration() const { return m_duration; }
uint32_t AudioBuffer::channels() const { return m_channels; }
void AudioBuffer::set_data(const AudioData& data) {
Logger::info("buffer={} valid={}", m_buffer, (int)alIsBuffer(m_buffer));
Logger::info("buffer={} isBuffer={}", m_buffer, (int)alIsBuffer(m_buffer));
ALenum format;
if (data.channels == 1) {
format = AL_FORMAT_MONO16;
@@ -24,9 +22,9 @@ void AudioBuffer::set_data(const AudioData& data) {
}
m_channels = data.channels;
Logger::info("channels={} rate={} samples={} bytes={} format={}",
data.channels, data.sample_rate, data.pcm.size(),
data.pcm.size() * sizeof(int16_t), format);
Logger::debug("channels={} rate={} samples={} bytes={} format={}",
data.channels, data.sample_rate, data.pcm.size(),
data.pcm.size() * sizeof(int16_t), format);
alBufferData(m_buffer, format, data.pcm.data(),
static_cast<ALsizei>(data.pcm.size() * sizeof(int16_t)),
static_cast<ALsizei>(data.sample_rate));
@@ -35,7 +33,7 @@ void AudioBuffer::set_data(const AudioData& data) {
alGetBufferi(m_buffer, AL_SIZE, &size);
check_al_error();
Logger::info("buffer size={}", size);
Logger::debug("buffer size={}", size);
m_duration = static_cast<float>(data.pcm.size()) /
(data.channels * data.sample_rate);
}

View File

@@ -1,13 +1,19 @@
#include "Cubed/audio/audio_engine.hpp"
#include "Cubed/audio/audio_error.hpp"
#include "Cubed/gameplay/client_world.hpp"
#include "Cubed/gameplay/network_client.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include <stdexcept>
using namespace google::protobuf;
namespace {
constexpr std::size_t OPUS_MAX_PACKET_SIZE = 400;
}
namespace Cubed {
AudioEngine::AudioEngine(Config& config) : m_config(config) {};
AudioEngine::AudioEngine(Config& config)
: m_recording(*this), m_config(config) {};
AudioEngine::~AudioEngine() {
if (!m_init) {
@@ -17,17 +23,40 @@ AudioEngine::~AudioEngine() {
m_bgm.reset();
m_pool.reset();
m_sounds.clear();
m_voice_source.reset();
m_low_pass_filter.reset();
m_underwater_effect.reset();
m_underwater_slot.reset();
opus_encoder_destroy(m_encoder);
opus_decoder_destroy(m_decoder);
alcMakeContextCurrent(nullptr);
alcDestroyContext(context);
alcCloseDevice(device);
}
void AudioEngine::init() {
{
int error;
m_encoder = opus_encoder_create(AudioRecording::SAMPLE_RATE,
1, // Mono
OPUS_APPLICATION_VOIP, &error);
if (error != OPUS_OK) {
Logger::error("Can't Create Opus Encoder Error {}", error);
}
opus_encoder_ctl(m_encoder, OPUS_SET_BITRATE(24000));
opus_encoder_ctl(m_encoder, OPUS_SET_COMPLEXITY(5));
opus_encoder_ctl(m_encoder, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE));
}
{
int error;
m_decoder = opus_decoder_create(AudioRecording::SAMPLE_RATE, 1, &error);
if (error != OPUS_OK) {
Logger::error("Can't Create Opus Encoder Error {}", error);
}
}
device = alcOpenDevice(NULL);
if (!device) {
throw std::runtime_error("Failed to open OpenAL device.");
@@ -51,7 +80,7 @@ void AudioEngine::init() {
m_low_pass_filter = std::make_unique<AudioFilter>();
m_low_pass_filter->set_lowpass(1.0f, 0.15f);
m_low_pass_filter->set_lowpass(1.0f, 0.1f);
m_underwater_effect = std::make_unique<AudioEffect>();
m_underwater_effect->set_reverb(0.8f, 0.3162f, 0.01f);
@@ -62,10 +91,10 @@ void AudioEngine::init() {
alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
check_al_error();
m_recording.init();
m_music_volume = m_config.get("volume.music", 1.0f);
m_sfx_volume = m_config.get("volume.SFX", 1.0f);
m_player_voice_volume = m_config.get("volume.player_voice", 1.0f);
m_sounds.init();
m_bgm = std::make_unique<AudioSource>(m_music_volume);
@@ -73,7 +102,8 @@ void AudioEngine::init() {
m_bgm->set_buffer_2d(m_sounds.get_buffer("bgm/bgm001.mp3"));
m_fade_map.try_emplace("bgm", m_bgm.get(), 5.0f, 2.0f);
m_voice_source = std::make_unique<AudioStreamSource>();
m_voice_source->set_volume(m_player_voice_volume);
ALCint max_mono = 0;
alcGetIntegerv(device, ALC_MONO_SOURCES, 1, &max_mono);
@@ -84,8 +114,8 @@ void AudioEngine::init() {
}
Logger::info("Set Source Pool Size {}", static_cast<int>(max_mono));
// Reserve a source for BGM
m_pool = std::make_shared<SourcePool>(max_mono - 1);
// Reserve two sources for BGM and voice
m_pool = std::make_shared<SourcePool>(max_mono - 2);
Logger::info("Audio Engine Init Success");
@@ -144,10 +174,10 @@ void AudioEngine::play_2d(const std::string& sound, bool check) {
return;
}
auto* source = m_pool->acquire();
source->set_volume(m_sfx_volume);
if (!source) {
Logger::error("Source is Full");
}
source->set_volume(m_sfx_volume);
try {
auto& buffer = m_sounds.get_buffer(sound);
@@ -181,14 +211,19 @@ void AudioEngine::update() {
fade.update();
}
m_pool->update();
m_recording.update();
}
void AudioEngine::reload_config() {
m_music_volume = m_config.get("volume.music", 1.0f);
m_sfx_volume = m_config.get("volume.SFX", 1.0f);
m_player_voice_volume = m_config.get("volume.player_voice", 1.0f);
if (m_bgm) {
m_bgm->set_target_volume(m_music_volume);
}
if (m_voice_source) {
m_voice_source->set_volume(m_player_voice_volume);
}
}
void AudioEngine::underwater_change(bool underwater) {
@@ -201,22 +236,77 @@ void AudioEngine::underwater_change(bool underwater) {
}
for (auto& source : m_pool->sources()) {
if (m_underwater) {
source.set_filter(*m_low_pass_filter);
source.set_effect_slot(*m_underwater_slot);
source->set_filter(*m_low_pass_filter);
source->set_effect_slot(*m_underwater_slot);
} else {
source.clear_filter();
source.clear_effect_slot();
source->clear_filter();
source->clear_effect_slot();
}
}
if (underwater) {
m_bgm->set_filter(*m_low_pass_filter);
m_voice_source->set_filter(*m_low_pass_filter);
m_voice_source->set_effect_slot(*m_underwater_slot);
} else {
m_bgm->clear_filter();
m_voice_source->clear_filter();
m_voice_source->clear_effect_slot();
}
Logger::info("Under Water Change {}", m_underwater);
}
float& AudioEngine::bgm_target_volume() { return m_bgm->target_volume(); }
void AudioEngine::set_client(std::weak_ptr<NetworkClient> client) {
m_client = client;
}
void AudioEngine::send_voice(
const std::array<int16_t, AudioRecording::FRAME_SAMPLES>& pcm) {
if (auto c = m_client.lock()) {
if (!c->world().enable_voice_chat()) {
return;
}
std::array<uint8_t, OPUS_MAX_PACKET_SIZE> opus;
int len =
opus_encode(m_encoder, pcm.data(), AudioRecording::FRAME_SAMPLES,
opus.data(), opus.size());
if (len < 0) {
Logger::error("Opus encode failed: {}", opus_strerror(len));
return;
}
Arena arena;
auto msg = Arena::Create<VoiceMsg>(&arena);
msg->set_uuid(c->world().get_player().get_uuid());
msg->set_opus_data(reinterpret_cast<char*>(opus.data()), len);
auto* pos = msg->mutable_pos();
auto p = c->world().get_player().get_player_pos();
pos->set_x(p.x);
pos->set_y(p.y);
pos->set_z(p.z);
c->send(make_packet(*msg));
}
}
void AudioEngine::receive_voice(std::span<const char> opus,
const glm::vec3& pos) {
std::array<int16_t, AudioRecording::FRAME_SAMPLES> pcm;
int len =
opus_decode(m_decoder, reinterpret_cast<const uint8_t*>(opus.data()),
opus.size(), pcm.data(), AudioRecording::FRAME_SAMPLES, 0);
if (len < 0) {
Logger::error("Opus decode failed: {}", opus_strerror(len));
return;
}
m_voice_source->set_pos(pos);
m_voice_source->push_pcm(std::span(pcm.data(), len),
AudioRecording::SAMPLE_RATE);
}
AudioRecording& AudioEngine::audio_recording() { return m_recording; }
const AudioRecording& AudioEngine::audio_recording() const {
return m_recording;
}
} // namespace Cubed

View File

@@ -46,8 +46,8 @@ AudioData AudioLoader::load_wav(const std::filesystem::path& path) {
drwav_read_pcm_frames_s16(&wav, wav.totalPCMFrameCount, data.pcm.data());
drwav_uninit(&wav);
Logger::info("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
Logger::debug("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
return data;
}
@@ -70,8 +70,8 @@ AudioData AudioLoader::load_mp3(const std::filesystem::path& path) {
data.pcm.assign(pcm, pcm + frame_count * config.channels);
drmp3_free(pcm, nullptr);
Logger::info("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
Logger::debug("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
return data;
}
@@ -93,8 +93,8 @@ AudioData AudioLoader::load_flac(const std::filesystem::path& path) {
data.pcm.assign(pcm, pcm + frame_count * channels);
drflac_free(pcm, nullptr);
Logger::info("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
Logger::debug("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
return data;
}
@@ -134,8 +134,8 @@ AudioData AudioLoader::load_ogg(const std::filesystem::path& path) {
data.sample_rate = sample_rate;
data.pcm = std::move(pcm);
Logger::info("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
Logger::debug("{} channels={} rate={} samples={}", path.filename().string(),
data.channels, data.sample_rate, data.pcm.size());
return data;
}

View File

@@ -0,0 +1,77 @@
#include "Cubed/audio/audio_recording.hpp"
#include "Cubed/audio/audio_engine.hpp"
#include "Cubed/tools/log.hpp"
#include <al.h>
namespace Cubed {
AudioRecording::AudioRecording(AudioEngine& engine)
: m_engine(engine) {
};
AudioRecording::~AudioRecording() {
if (m_capture) {
if (m_recording) {
stop();
}
alcCaptureCloseDevice(m_capture);
}
}
void AudioRecording::init() {
m_capture =
alcCaptureOpenDevice(nullptr, SAMPLE_RATE, AL_FORMAT_MONO16, 4096);
if (m_capture) {
Logger::info("Open Audio Capture Success");
} else {
Logger::error("Fail to Open Audio Capture Device");
}
ALCint freq = 0;
alcGetIntegerv(m_capture, ALC_FREQUENCY, 1, &freq);
Logger::info("Capture frequency={}", freq);
}
void AudioRecording::start() {
if (m_recording) {
return;
}
ALCint samples;
alcGetIntegerv(m_capture, ALC_CAPTURE_SAMPLES, 1, &samples);
std::vector<int16_t> dump(samples);
alcCaptureSamples(m_capture, dump.data(), samples);
alcCaptureStart(m_capture);
m_recording = true;
}
void AudioRecording::stop() {
if (!m_recording) {
return;
}
alcCaptureStop(m_capture);
m_recording = false;
}
bool AudioRecording::is_recording() const { return m_recording; }
void AudioRecording::update() {
if (!m_recording || !m_capture) {
return;
}
ALCint available = 0;
alcGetIntegerv(m_capture, ALC_CAPTURE_SAMPLES, 1, &available);
while (available >= FRAME_SAMPLES) {
std::array<int16_t, FRAME_SAMPLES> pcm;
alcCaptureSamples(m_capture, pcm.data(), FRAME_SAMPLES);
send_voice(pcm);
available -= FRAME_SAMPLES;
}
}
void AudioRecording::send_voice(const std::array<int16_t, FRAME_SAMPLES>& pcm) {
m_engine.send_voice(pcm);
}
} // namespace Cubed

View File

@@ -91,12 +91,19 @@ void AudioSource::play_2d(const AudioBuffer& buffer) {
set_buffer_2d(buffer);
play();
}
void AudioSource::play_2d(std::unique_ptr<AudioBuffer> buffer) {
m_buffer = std::move(buffer);
play_2d(*m_buffer);
}
void AudioSource::play_3d(const AudioBuffer& buffer, const glm::vec3& pos) {
set_buffer_3d(buffer, pos);
play();
}
void AudioSource::play_3d(std::unique_ptr<AudioBuffer> buffer,
const glm::vec3& pos) {
m_buffer = std::move(buffer);
play_3d(*m_buffer, pos);
}
void AudioSource::stop() { alSourceStop(m_source); }
void AudioSource::pause() { alSourcePause(m_source); }
@@ -163,7 +170,7 @@ void AudioSource::reset() {
clear_filter();
clear_effect_slot();
m_buffer.reset();
m_duration = 0.0f;
m_target_volume = 1.0f;
m_using = false;

View File

@@ -0,0 +1,142 @@
#include "Cubed/audio/audio_stream_source.hpp"
#include "Cubed/audio/audio_error.hpp"
#include "Cubed/tools/log.hpp"
#include <cfloat>
#include <efx.h>
namespace Cubed {
AudioStreamSource::AudioStreamSource() {
alGenBuffers(NUM_BUFFERS, m_buffers.data());
alGenSources(1, &m_source);
alSourcei(m_source, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(m_source, AL_POSITION, 0.0f, 0.0f, 0.0f);
m_free_buffers.assign(m_buffers.begin(), m_buffers.end());
}
AudioStreamSource::~AudioStreamSource() {
stop();
alDeleteSources(1, &m_source);
alDeleteBuffers(NUM_BUFFERS, m_buffers.data());
}
void AudioStreamSource::push_pcm(std::span<const int16_t> pcm,
ALsizei sample_rate) {
if (!m_source) {
return;
}
unqueue_processed();
if (m_free_buffers.empty()) {
Logger::warn("Queue is full, dropping frame");
return;
}
ALuint buf = m_free_buffers.back();
m_free_buffers.pop_back();
alBufferData(buf, AL_FORMAT_MONO16, pcm.data(),
static_cast<ALsizei>(pcm.size() * sizeof(int16_t)),
sample_rate);
alSourceQueueBuffers(m_source, 1, &buf);
ALint state;
alGetSourcei(m_source, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING) {
alSourcePlay(m_source);
m_playing = true;
}
}
void AudioStreamSource::stop() {
if (!m_source) {
return;
}
alSourceStop(m_source);
alSourcei(m_source, AL_BUFFER, 0);
m_free_buffers.assign(m_buffers.begin(), m_buffers.end());
m_playing = false;
}
void AudioStreamSource::unqueue_processed() {
ALint processed = 0;
alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &processed);
while (processed-- > 0) {
ALuint buf;
alSourceUnqueueBuffers(m_source, 1, &buf);
m_free_buffers.push_back(buf);
}
}
void AudioStreamSource::set_volume(float volume) {
volume = std::clamp(volume, 0.0f, 1.0f);
alSourcef(m_source, AL_GAIN, volume);
}
void AudioStreamSource::set_pitch(float pitch) {
pitch = std::clamp(pitch, 0.0f, 1.0f);
alSourcef(m_source, AL_PITCH, pitch);
}
void AudioStreamSource::set_pos(glm::vec3 pos) {
alSourcei(m_source, AL_SOURCE_RELATIVE, AL_FALSE);
alSource3f(m_source, AL_POSITION, pos.x, pos.y, pos.z);
check_al_error();
alSourcef(m_source, AL_REFERENCE_DISTANCE, 4.0f);
alSourcef(m_source, AL_ROLLOFF_FACTOR, 1.0f);
alSourcef(m_source, AL_MAX_DISTANCE, 48.0f);
}
void AudioStreamSource::reset() {
alSourceStop(m_source);
alSourcei(m_source, AL_BUFFER, 0);
alSourcef(m_source, AL_GAIN, 1.0f);
alSourcef(m_source, AL_PITCH, 1.0f);
alSource3f(m_source, AL_POSITION, 0.0f, 0.0f, 0.0f);
alSource3f(m_source, AL_VELOCITY, 0.0f, 0.0f, 0.0f);
alSource3f(m_source, AL_DIRECTION, 0.0f, 0.0f, 0.0f);
alSourcef(m_source, AL_REFERENCE_DISTANCE, 1.0f);
alSourcef(m_source, AL_ROLLOFF_FACTOR, 1.0f);
alSourcef(m_source, AL_MAX_DISTANCE, FLT_MAX);
alSourcef(m_source, AL_CONE_INNER_ANGLE, 360.0f);
alSourcef(m_source, AL_CONE_OUTER_ANGLE, 360.0f);
alSourcef(m_source, AL_CONE_OUTER_GAIN, 0.0f);
alSourcei(m_source, AL_LOOPING, AL_FALSE);
alSourcei(m_source, AL_SOURCE_RELATIVE, AL_FALSE);
alSourcef(m_source, AL_SEC_OFFSET, 0.0f);
clear_filter();
clear_effect_slot();
}
void AudioStreamSource::set_filter(const AudioFilter& filter) {
alSourcei(m_source, AL_DIRECT_FILTER, filter.filter());
}
void AudioStreamSource::clear_filter() {
alSourcei(m_source, AL_DIRECT_FILTER, AL_FILTER_NULL);
}
void AudioStreamSource::set_effect_slot(const AudioEffectSlot& slot) {
alSource3i(m_source, AL_AUXILIARY_SEND_FILTER, slot.slot(), 0,
AL_FILTER_NULL);
}
void AudioStreamSource::clear_effect_slot() {
alSource3i(m_source, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, 0,
AL_FILTER_NULL);
}
} // namespace Cubed

View File

@@ -1,24 +1,32 @@
#include "Cubed/audio/source_pool.hpp"
namespace Cubed {
SourcePool::SourcePool(size_t size) { m_sources.resize(size); }
SourcePool::SourcePool(size_t size) {
m_sources.reserve(size);
for (size_t i = 0; i < size; ++i) {
m_sources.emplace_back(std::make_unique<AudioSource>());
}
}
SourcePool::~SourcePool() { m_sources.clear(); }
void SourcePool::update() {
for (auto& source : m_sources) {
if (source.in_use() && source.state() == AudioState::STOPPED) {
source.reset();
for (auto& source_ptr : m_sources) {
if (source_ptr->in_use() &&
source_ptr->state() == AudioState::STOPPED) {
source_ptr->reset();
}
}
}
AudioSource* SourcePool::acquire() {
for (auto& source : m_sources) {
if (!source.in_use()) {
source.mark_in_use();
return &source;
for (auto& source_ptr : m_sources) {
if (!source_ptr->in_use()) {
source_ptr->mark_in_use();
return source_ptr.get();
}
}
return nullptr;
}
std::vector<AudioSource>& SourcePool::sources() { return m_sources; }
std::vector<std::unique_ptr<AudioSource>>& SourcePool::sources() {
return m_sources;
}
} // namespace Cubed

View File

@@ -2,6 +2,7 @@
#include "Cubed/tools/system_info.hpp"
#include "Cubed/tools/system_window_manager.hpp"
#include "Cubed/ui/rect.hpp"
#include "version.hpp"
#include <SDL3/SDL_video.h>
@@ -19,15 +20,33 @@ std::unique_ptr<DebugCollector>& DebugCollector::get_ptr() {
}
void DebugCollector::destory() { get_ptr().reset(); }
void DebugCollector::init(int width, int height) {
constexpr float SCALE = 0.6f;
constexpr float SCALE = 0.7f;
constexpr Color COLOR = Color::GRAY;
constexpr float ALPHA = 0.6f;
m_widget.set_window_size(width, height);
m_widget.set_spacing(15);
m_widget.set_anchor(Anchor::TOP_LEFT);
m_widget.set_offset({0, 5});
m_widget.set_child_anchor(ColumnLayoutAnchor::LEFT);
auto add_label = [&](std::string_view text, std::string_view key = "") {
auto& label = m_widget.add_child<Label>();
auto rect = std::make_unique<Rect>(&label);
rect->set_color(COLOR).set_alpha(ALPHA).set_fill_parent(true);
label.set_background(std::move(rect));
label.set_color(Color::WHITE).set_text(text).set_scale(SCALE);
if (!key.empty()) {
auto [_, insert] =
m_component.try_emplace(std::string(key), &label);
if (!insert) {
Logger::error("DebugCollector Key {} already esist", key);
}
}
};
// version_text
auto& version_text = m_widget.add_child<Label>();
std::string version{"Version: " CUBED_VERSION};
#ifdef DEBUG_MODE
@@ -36,87 +55,56 @@ void DebugCollector::init(int width, int height) {
version.append("-release");
#endif
version_text.set_color(Color::WHITE).set_text(version).set_scale(SCALE);
add_label(version);
{
auto& compiler = m_widget.add_child<Label>();
compiler.set_text(Tools::get_compiler_info()).set_scale(SCALE);
}
add_label(Tools::get_compiler_info());
// fps
auto& fps_text = m_widget.add_child<Label>();
fps_text.set_text("FPS: 0").set_scale(SCALE);
m_component.try_emplace("fps", &fps_text);
add_label("FPS: 0", "fps");
// player_pos
auto& player_pos_text = m_widget.add_child<Label>();
player_pos_text.set_text("x: 0.00 y: 0.00 z: 0.00").set_scale(SCALE);
m_component.try_emplace("player_pos", &player_pos_text);
add_label("x: 0.00 y: 0.00 z: 0.00", "player_pos");
// rendered_chunk
auto& rendered_chunk_text = m_widget.add_child<Label>();
rendered_chunk_text.set_text("Rendered Chunk: 0").set_scale(SCALE);
m_component.try_emplace("rendered_chunk", &rendered_chunk_text);
add_label("Rendered Chunk: 0", "rendered_chunk");
// rss
auto& rss_text = m_widget.add_child<Label>();
rss_text.set_text("RSS: 0mb").set_scale(SCALE);
m_component.try_emplace("rss", &rss_text);
add_label("RSS: 0mb", "rss");
// os
std::string os;
auto& os_text = m_widget.add_child<Label>();
os_text.set_scale(SCALE);
std::string os_text;
if (Tools::get_os_version(os)) {
os_text.set_text("OS: " + os);
os_text = "OS: " + os;
Logger::info("OS System: {}", os);
} else {
os_text.set_text("OS: Unknown");
os_text = "OS: Unknown";
}
add_label(os_text);
{
std::string wm{"WM: "};
wm.append(Tools::detect_wm());
auto& wm_label = m_widget.add_child<Label>();
wm_label.set_text(wm).set_scale(SCALE);
add_label(wm);
}
// cpu
auto& cpu_text = m_widget.add_child<Label>();
cpu_text.set_text("CPU: " + Tools::get_cpu_info()).set_scale(SCALE);
add_label("CPU: " + Tools::get_cpu_info());
// gpu
auto& gpu_text = m_widget.add_child<Label>();
gpu_text
.set_text(std::string{"GPU: "} +
reinterpret_cast<const char*>(glGetString(GL_RENDERER)))
.set_scale(SCALE);
add_label(std::string{"GPU: "} +
reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
// opengl_version
auto& opengl_version_text = m_widget.add_child<Label>();
opengl_version_text
.set_text("OpenGL: " + std::to_string(GLVersion.major) + "." +
std::to_string(GLVersion.minor))
.set_scale(SCALE);
{
auto& video_driver = m_widget.add_child<Label>();
video_driver
.set_text(
std::format("VideoDiver: {}", SDL_GetCurrentVideoDriver()))
.set_scale(SCALE);
}
add_label("OpenGL: " + std::to_string(GLVersion.major) + "." +
std::to_string(GLVersion.minor));
add_label(std::format("VideoDiver: {}", SDL_GetCurrentVideoDriver()));
// speed
auto& speed_text = m_widget.add_child<Label>();
speed_text.set_text("Speed: 0 m/s").set_scale(SCALE);
m_component.try_emplace("speed", &speed_text);
{
auto& window_size = m_widget.add_child<Label>();
window_size.set_text("Window W: {} H: {}").set_scale(SCALE);
m_component.try_emplace("window_size", &window_size);
}
{
auto& frame_size = m_widget.add_child<Label>();
frame_size.set_text("FrameBuffer W: {} H: {}").set_scale(SCALE);
m_component.try_emplace("frame_buffer", &frame_size);
}
add_label("Speed: 0 m/s", "speed");
add_label("Window W: {} H: {}", "window_size");
add_label("FrameBuffer W: {} H: {}", "frame_buffer");
}
Widget& DebugCollector::get_widget() { return m_widget; }

View File

@@ -653,7 +653,6 @@ void ClientPlayer::init(std::string_view name) {
glm::ivec3 block = glm::floor(m_player_pos);
block.y -= 1;
BlockType id = m_world.get_block_tpye(block);
Logger::info("player Block {} Walk Sound", id);
if (id == 0) {
return;
}
@@ -661,7 +660,7 @@ void ClientPlayer::init(std::string_view name) {
std::string sound = "block/" + name + "/walk.ogg";
auto& audio = m_world.get_audio();
audio.play_3d(sound, m_player_pos);
Logger::info("Player block {} walk sound", name);
Logger::debug("Player block {} walk sound", name);
});
}

View File

@@ -6,6 +6,7 @@
#include "Cubed/gameplay/packet.hpp"
#include "Cubed/scene/world_scene.hpp"
#include "Cubed/tools/math_tools.hpp"
#include "Cubed/tools/time_tools.hpp"
#include <absl/container/inlined_vector.h>
#include <numbers>
@@ -474,6 +475,11 @@ void ClientWorld::init(std::string_view player_name,
m_audio.play_bgm();
}
void ClientWorld::receive_login_rsp(LoginRsp& rsp) {
m_voice_chat = rsp.voice_chat();
start_client_thread(rsp.uuid());
}
void ClientWorld::start_client_thread(std::string_view uuid) {
if (m_game_running) {
Logger::error("Game Already Running");
@@ -481,6 +487,7 @@ void ClientWorld::start_client_thread(std::string_view uuid) {
}
// response
m_player.set_uuid(uuid);
m_client_thread = std::jthread([this](std::stop_token token) {
m_game_running = true;
client_run(token);
@@ -725,6 +732,7 @@ AABB ClientWorld::get_block_aabb(const glm::ivec3& pos) {
}
AudioEngine& ClientWorld::get_audio() { return m_audio; }
const AudioEngine& ClientWorld::get_audio() const { return m_audio; }
Config& ClientWorld::get_config() { return m_config; }
WorldScene& ClientWorld::world_scene() { return m_world_scene; }
void ClientWorld::set_direct_exit() { m_exit_direct = true; }
@@ -750,6 +758,29 @@ void ClientWorld::request_exit() {
}
}
void ClientWorld::receive_chat_message(ChatMsg& msg) {
Color color = color_from_int(msg.color());
m_message_queue.emplace(msg.name(), msg.msg(), color, msg.system_msg(),
Tools::get_time_ticks());
}
void ClientWorld::receive_voice_message(VoiceMsg& msg) {
if (!m_voice_chat) {
return;
}
glm::vec3 pos{msg.pos().x(), msg.pos().y(), msg.pos().z()};
m_voice_queue.emplace(msg.opus_data(), pos);
}
bool ClientWorld::enable_voice_chat() const { return m_voice_chat.load(); }
void ClientWorld::send_chat_message(ChatMessage& message) {
Arena arena;
auto msg = Arena::Create<ChatMsg>(&arena);
msg->set_name(message.player);
msg->set_msg(message.text);
m_client->send(make_packet(*msg));
}
void ClientWorld::update(float delta_time) {
m_player.update(delta_time);
@@ -916,6 +947,15 @@ void ClientWorld::update(float delta_time) {
for (auto& [pos, timer] : m_timers) {
timer.update(delta_time);
}
ChatMessage message;
while (m_message_queue.try_pop(message)) {
m_world_scene.handle_chat_message(message);
}
VoiceMessage vm;
while (m_voice_queue.try_pop(vm)) {
m_audio.receive_voice(vm.data, vm.pos);
}
}
bool ClientWorld::handle_event(const Event& e) {

View File

@@ -83,11 +83,7 @@ asio::awaitable<void> NetworkClient::read_loop() {
auto* rsp = Arena::Create<LoginRsp>(&arena);
Logger::info("Client: Receive Login rsp");
if (decode_packet(*rsp, body_data, header)) {
if (rsp->success()) {
m_world.start_client_thread(rsp->uuid());
} else {
Logger::error("Connected Server Fail");
}
m_world.receive_login_rsp(*rsp);
}
} break;
case std::to_underlying(PacketEnum::CHUNK_DATA_RSP): {
@@ -135,6 +131,18 @@ asio::awaitable<void> NetworkClient::read_loop() {
m_world.receive_player_water_sound(*rsp);
}
} break;
case std::to_underlying(PacketEnum::CHAT_MSG): {
auto* msg = Arena::Create<ChatMsg>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_world.receive_chat_message(*msg);
}
} break;
case std::to_underlying(PacketEnum::VOICE_MSG): {
auto* msg = Arena::Create<VoiceMsg>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_world.receive_voice_message(*msg);
}
}
}
}
} catch (const asio::system_error& e) {
@@ -222,5 +230,5 @@ void NetworkClient::set_error(std::string_view error) {
m_error_string = error;
m_connect_error = true;
}
ClientWorld& NetworkClient::world() { return m_world; }
} // namespace Cubed

View File

@@ -4,14 +4,17 @@
#include "Cubed/gameplay/session.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/math_tools.hpp"
#include "Cubed/tools/uuid.hpp"
#include <nlohmann/json.hpp>
#include <ranges>
#include <utility>
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace google::protobuf;
namespace fs = std::filesystem;
using nlohmann::json;
namespace Cubed {
ServerWorld::ServerWorld(Config& config) : m_config(config) {}
@@ -197,6 +200,21 @@ void ServerWorld::init_world() {
m_cave_carcer.init(ChunkGenerator::seed());
m_river_worm.init(ChunkGenerator::seed());
m_enable_filter = m_config.get("sensitive_filter", false);
Logger::info("sensitive filter {}", m_enable_filter.load());
m_voice_chat = m_config.get("voice_chat", true);
Logger::info("voice chat {}", m_voice_chat.load());
try {
fs::path path = std::format("{}SensitiveLexicon.json", ASSETS_PATH);
std::ifstream s{path};
json j = json::parse(s);
m_filter.load(j);
} catch (const std::exception& e) {
Logger::error("Load SensitiveLexicon.json Fail");
m_enable_filter = false;
}
// m_chunks.reserve(MAX_DISTANCE * MAX_DISTANCE * 4);
start_thread_pool();
@@ -680,20 +698,27 @@ void ServerWorld::handle_player_login(const std::string& name,
auto* rsp = Arena::Create<LoginRsp>(&arena);
rsp->set_success(true);
rsp->set_uuid(uuid);
rsp->set_voice_chat(m_voice_chat);
session->send(make_packet(*rsp), 0);
boardcast_message("Server", std::format("Player {} Join Game", name),
Color::YELLOW, true);
}
void ServerWorld::handle_player_exit(const std::string& uuid) {
std::shared_ptr<Session> exit_session;
ChunkPosSet old_set;
std::string name;
{
std::lock_guard lock(m_player_mutex);
auto it = m_players.find(uuid);
if (it != m_players.end()) {
Logger::info("Player {} Exit the Server", it->second.get_name());
name = it->second.get_name();
Logger::info("Player {} Exit the Server", name);
exit_session = it->second.get_session();
old_set = std::move(it->second.get_chunk_pos_set());
m_players.erase(it);
} else {
Logger::error("Player {} isn't in Server", uuid);
return;
@@ -723,6 +748,9 @@ void ServerWorld::handle_player_exit(const std::string& uuid) {
s->send(make_packet(*rsp), 0);
}
}
boardcast_message("Server", std::format("Player {} Exit Game", name),
Color::YELLOW, true);
}
glm::vec3 ServerWorld::get_player_pos(const std::string& uuid) const {
@@ -753,6 +781,58 @@ void ServerWorld::handle_chunk_req(int task_id, const std::string& uuid,
[task_id, uuid, pos, this]() { send_chunk(task_id, uuid, pos); });
}
void ServerWorld::handle_chat_message(ChatMsg& msg) {
std::string name = msg.name();
std::string message = msg.msg();
auto pool = m_net_thread_pool.load();
pool->enqueue([this, player = std::move(name), m = std::move(message)]() {
boardcast_message(player, m);
});
}
void ServerWorld::handle_voice_message(VoiceMsg& msg) {
if (!m_voice_chat) {
return;
}
auto pool = m_net_thread_pool.load();
std::string uuid = msg.uuid();
std::string data = msg.opus_data();
auto pos = msg.pos();
glm::vec3 p{pos.x(), pos.y(), pos.z()};
pool->enqueue([this, uuid = std::move(uuid), data = std::move(data), p]() {
std::vector<std::shared_ptr<Session>> session;
{
std::shared_lock lock(m_player_mutex);
for (auto& [key, player] : m_players) {
if (key == uuid) {
continue;
}
if (Math::distance2(p, player.get_pos()) > 48.0f * 48.0f) {
continue;
}
session.emplace_back(player.get_session());
}
}
Arena arena;
auto msg = Arena::Create<VoiceMsg>(&arena);
msg->set_uuid(uuid);
msg->set_opus_data(data);
auto pos = msg->mutable_pos();
pos->set_x(p.x);
pos->set_y(p.y);
pos->set_z(p.z);
for (auto& s : session) {
s->send(make_packet(*msg), 5);
}
});
}
void ServerWorld::handle_block_change(const BlockChangeReq& req) {
float x = std::floor(req.pos().x());
float y = std::floor(req.pos().y());
@@ -861,6 +941,36 @@ void ServerWorld::send_server_stop() {
Logger::info("Send Server Mesaage Success");
}
void ServerWorld::boardcast_message(const std::string& name,
const std::string& message, Color color,
bool system_msg) {
std::vector<std::shared_ptr<Session>> m_session;
{
std::shared_lock lock(m_player_mutex);
for (auto& [_, p] : m_players) {
m_session.emplace_back(p.get_session());
}
}
Arena arena;
auto msg = Arena::Create<ChatMsg>(&arena);
if (m_enable_filter) {
msg->set_msg(m_filter.filter(message));
msg->set_name(m_filter.filter(name));
} else {
msg->set_msg(message);
msg->set_name(name);
}
msg->set_color(std::to_underlying(color));
msg->set_system_msg(system_msg);
for (auto& s : m_session) {
s->send(make_packet(*msg));
}
}
int ServerWorld::chunk_load_style() const {
return std::to_underlying(m_chunk_load_style.load());
}

View File

@@ -99,6 +99,18 @@ asio::awaitable<void> Session::read_loop() {
m_server_world.sync_player_water_sound(*req);
}
}
if (cmd_id == std::to_underlying(PacketEnum::CHAT_MSG)) {
auto* msg = Arena::Create<ChatMsg>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_server_world.handle_chat_message(*msg);
}
}
if (cmd_id == std::to_underlying(PacketEnum::VOICE_MSG)) {
auto* msg = Arena::Create<VoiceMsg>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_server_world.handle_voice_message(*msg);
}
}
}
} catch (const asio::system_error& e) {
auto ec = e.code();

View File

@@ -7,6 +7,7 @@ message LoginReq {
message LoginRsp {
bool success = 1;
string uuid = 2;
bool voice_chat = 3;
}
message LogoutReq {

14
src/proto/chat/chat.proto Normal file
View File

@@ -0,0 +1,14 @@
syntax = "proto3";
import "common/vector3.proto";
message ChatMsg {
string name = 1;
string msg = 2;
int32 color = 3;
bool system_msg = 4;
}
message VoiceMsg {
string uuid = 1;
Vec3 pos = 2;
bytes opus_data = 3;
}

View File

@@ -9,4 +9,5 @@ import "system/ping.proto";
import "system/pong.proto";
import "world/chunk_data.proto";
import "world/block_change.proto";
import "world/time.proto";
import "world/time.proto";
import "chat/chat.proto";

View File

@@ -183,6 +183,9 @@ void Renderer::render_lable(const Label& label) {
Font::get().text_texture()->bind(0);
auto& data = label.data();
if (!data.m_vao) {
return;
}
auto pos = label.pos();
auto& text_style = label.text_style();
auto color = color_value(text_style.color);

View File

@@ -29,6 +29,8 @@ void SettingsScene::on_enter() {
m_slider_variable.sfx = config.get("volume.SFX", m_slider_variable.sfx);
m_slider_variable.rendering_distance = config.get(
"world.rendering_distance", m_slider_variable.rendering_distance);
m_slider_variable.player_voice =
config.get("volume.player_voice", m_slider_variable.player_voice);
}
void SettingsScene::on_leave() {
save_and_apply();
@@ -54,6 +56,7 @@ void SettingsScene::save_and_apply() {
m_slider_variable.rendering_distance);
config.set("volume.SFX", m_slider_variable.sfx);
config.set("volume.music", m_slider_variable.music);
config.set("volume.player_voice", m_slider_variable.player_voice);
config.save_to_file();
auto& app = m_scene_manager.app();
app.audio().reload_config();

View File

@@ -70,9 +70,7 @@ void WorldScene::render(Renderer& renderer) {
}
}
bool WorldScene::handle_event(const Event& e) {
if (m_error_ui.has_error()) {
return m_error_ui.handle_event(e);
}
return std::visit(
Overloaded{[this](const MouseMoveEvent& e) {
if (handle_mouse_move_event(e)) {
@@ -98,7 +96,12 @@ bool WorldScene::handle_event(const Event& e) {
}
return false;
},
[](const TextInputEvent&) { return false; },
[this](const TextInputEvent& e) {
if (handle_text_input_event(e)) {
return true;
}
return false;
},
[this](const WindowResizeEvent& e) {
handle_window_resize_event(e);
return false;
@@ -110,7 +113,7 @@ bool WorldScene::handle_event(const Event& e) {
}
void WorldScene::on_enter() {
auto& param = m_scene_manager.world_scene_param();
load_config();
m_error_ui.init();
if (param.host_game) {
@@ -136,7 +139,7 @@ void WorldScene::on_enter() {
m_dev_panel.init();
m_pasue_menu.init();
m_hud_ui.init();
m_scene_manager.app().audio().set_client(m_client);
m_scene_manager.app().window().set_game_running(true);
} catch (const std::exception& e) {
m_error_ui.set_error(e.what());
@@ -158,6 +161,7 @@ void WorldScene::on_re_enter() {
m_error_ui.on_re_enter();
m_pasue_menu.on_re_enter();
m_client_world.reload_config();
load_config();
auto width = m_scene_manager.app().renderer().window_width();
auto height = m_scene_manager.app().renderer().window_height();
@@ -165,7 +169,27 @@ void WorldScene::on_re_enter() {
WindowResizeEvent{static_cast<int>(width), static_cast<int>(height)});
}
void WorldScene::load_config() {
auto type = m_scene_manager.app().config().get("voice_input", "PTT");
if (type == "off") {
m_input_type = VoiceInputType::OFF;
m_client_world.get_audio().audio_recording().stop();
} else if (type == "PTT") {
m_input_type = VoiceInputType::PTT;
m_client_world.get_audio().audio_recording().stop();
} else if (type == "always") {
m_input_type = VoiceInputType::ALWAYS;
m_client_world.get_audio().audio_recording().start();
}
}
bool WorldScene::handle_mouse_move_event(const MouseMoveEvent& e) {
if (m_error_ui.has_error()) {
return m_error_ui.handle_event(e);
}
if (m_chatting) {
return true;
}
if (m_paused) {
if (m_pasue_menu.handle_event(e)) {
return true;
@@ -186,6 +210,12 @@ bool WorldScene::handle_mouse_move_event(const MouseMoveEvent& e) {
return false;
}
bool WorldScene::handle_mouse_button_event(const MouseButtonEvent& e) {
if (m_error_ui.has_error()) {
return m_error_ui.handle_event(e);
}
if (m_chatting) {
return true;
}
if (m_paused) {
if (m_pasue_menu.handle_event(e)) {
return true;
@@ -206,23 +236,26 @@ bool WorldScene::handle_mouse_button_event(const MouseButtonEvent& e) {
}
bool WorldScene::handle_window_resize_event(const WindowResizeEvent& e) {
if (m_pasue_menu.handle_event(e)) {
return true;
}
if (m_hud_ui.handle_event(e)) {
return true;
}
if (m_camera.handle_event(e)) {
return true;
}
m_error_ui.handle_event(e);
m_pasue_menu.handle_event(e);
m_hud_ui.handle_event(e);
m_camera.handle_event(e);
// world event needs to be processed last
if (m_client_world.handle_event(e)) {
return true;
}
m_client_world.handle_event(e);
return false;
}
bool WorldScene::handle_mouse_wheel_event(const MouseWheelEvent& e) {
if (m_error_ui.has_error()) {
return m_error_ui.handle_event(e);
}
if (m_chatting) {
return true;
}
if (m_paused) {
if (m_pasue_menu.handle_event(e)) {
return true;
@@ -242,8 +275,15 @@ bool WorldScene::handle_mouse_wheel_event(const MouseWheelEvent& e) {
return false;
}
bool WorldScene::handle_key_event(const KeyEvent& e) {
if (m_error_ui.has_error()) {
return m_error_ui.handle_event(e);
}
if (e.key == Key::ESCAPE && e.action == KeyAction::PRESS) {
if (m_chatting && !m_paused) {
set_chatting(false, false);
return true;
}
bool pasued = pause();
pasued = !pasued;
set_pause(pasued);
@@ -257,6 +297,35 @@ bool WorldScene::handle_key_event(const KeyEvent& e) {
m_show_dev_pannel = !m_show_dev_pannel;
return true;
}
if (e.key == Key::T && e.action == KeyAction::PRESS) {
if (!m_chatting) {
set_chatting(true, true);
return true;
}
}
if (e.key == Key::ENTER && e.action == KeyAction::PRESS) {
if (m_chatting) {
set_chatting(false, true);
return true;
}
}
if (e.key == Key::V) {
if (m_input_type == VoiceInputType::PTT) {
auto& recording = m_client_world.get_audio().audio_recording();
if (e.action == KeyAction::PRESS) {
recording.start();
return true;
}
if (e.action == KeyAction::RELEASE) {
recording.stop();
return true;
}
}
}
if (m_paused) {
if (m_pasue_menu.handle_event(e)) {
return true;
@@ -265,6 +334,9 @@ bool WorldScene::handle_key_event(const KeyEvent& e) {
if (m_hud_ui.handle_event(e)) {
return true;
}
if (m_chatting) {
return true;
}
if (m_camera.handle_event(e)) {
return true;
}
@@ -276,6 +348,17 @@ bool WorldScene::handle_key_event(const KeyEvent& e) {
return false;
}
bool WorldScene::handle_text_input_event(const TextInputEvent& e) {
if (m_error_ui.has_error()) {
return m_error_ui.handle_event(e);
}
if (m_paused) {
return m_pasue_menu.handle_text_input_event(e);
}
return m_hud_ui.handle_text_input_event(e);
}
Camera& WorldScene::camera() { return m_camera; }
SceneManager& WorldScene::scene_manager() { return m_scene_manager; }
ClientWorld& WorldScene::client_world() { return m_client_world; }
@@ -286,13 +369,34 @@ void WorldScene::set_pause(bool pause) {
return;
}
m_paused = pause;
set_mouse(pause);
}
void WorldScene::set_mouse(bool enable) {
auto& window = m_scene_manager.app().window();
window.set_game_running(!m_paused);
if (m_paused) {
window.set_game_running(!enable);
if (enable) {
m_client_world.reset_key_status();
}
}
void WorldScene::set_chatting(bool chatting, bool send) {
if (m_paused) {
m_hud_ui.set_chatting(false, false);
return;
}
m_chatting = chatting;
m_hud_ui.set_chatting(chatting, send);
set_mouse(chatting);
}
// Not thread safe
void WorldScene::handle_chat_message(ChatMessage& message) {
m_hud_ui.add_chat_message(message);
}
bool WorldScene::is_recording() const {
return m_client_world.get_audio().audio_recording().is_recording();
}
void WorldScene::set_error(std::string_view error) {
Logger::error("WorldScene Error Set {}", error);
m_error_ui.set_error(error);

View File

@@ -154,6 +154,28 @@ TextMesh Font::vertices(const std::string& text) {
return {std::move(vertices), max_x - min_x, max_y - min_y, 0, 0};
}
float Font::text_width(const std::string& text) {
auto& f = Font::get();
hb_buffer_t* buffer = hb_buffer_create();
hb_buffer_add_utf8(buffer, text.c_str(), text.size(), 0, text.size());
hb_buffer_guess_segment_properties(buffer);
hb_shape(f.m_hb_font, buffer, nullptr, 0);
unsigned int count = 0;
auto* positions = hb_buffer_get_glyph_positions(buffer, &count);
hb_position_t advance = 0;
for (unsigned int i = 0; i < count; ++i) {
advance += positions[i].x_advance;
}
hb_buffer_destroy(buffer);
return static_cast<float>(advance) / 64.0f;
}
const Texture* Font::text_texture() { return m_text_texture.get(); }
const std::string& Font::font_path() { return m_font_path; }

View File

@@ -0,0 +1,118 @@
#include "Cubed/tools/sensitive_filter.hpp"
#include <queue>
#include <utf8cpp/utf8.h>
using nlohmann::json;
namespace Cubed {
SensitiveFilter::SensitiveFilter() {
};
void SensitiveFilter::load(const nlohmann::json& j) {
trie.clear();
trie.emplace_back();
for (const auto& item : j["words"]) {
auto str = item.get<std::string>();
std::u32string word;
utf8::utf8to32(str.begin(), str.end(), std::back_inserter(word));
insert(word);
}
build();
}
std::string SensitiveFilter::filter(std::string_view str) {
if (!utf8::is_valid(str.begin(), str.end())) {
return {};
}
int state = 0;
std::vector<char32_t> text;
auto it = str.begin();
while (it != str.end()) {
text.push_back(utf8::next(it, str.end()));
}
std::vector<uint8_t> mask(text.size(), 0);
for (size_t i = 0; i < text.size(); i++) {
char32_t ch = text[i];
auto it = trie[state].next.find(ch);
while (state && it == trie[state].next.end()) {
state = trie[state].fail;
it = trie[state].next.find(ch);
}
if (it != trie[state].next.end()) {
state = it->second;
}
int t = state;
while (t) {
if (trie[t].end) {
size_t begin = i + 1 - trie[t].length;
for (size_t j = begin; j < begin + trie[t].length; j++)
mask[j] = true;
}
t = trie[t].fail;
}
}
std::string out;
for (size_t i = 0; i < text.size();) {
if (mask[i]) {
out += "***";
while (i < text.size() && mask[i])
++i;
} else {
// char32_t -> UTF8
utf8::append(text[i], std::back_inserter(out));
++i;
}
}
return out;
}
void SensitiveFilter::insert(const std::u32string& word) {
int now = 0;
for (char32_t ch : word) {
auto it = trie[now].next.find(ch);
if (it == trie[now].next.end()) {
trie[now].next[ch] = trie.size();
trie.emplace_back();
}
now = trie[now].next[ch];
}
trie[now].end = true;
trie[now].length = word.size();
}
void SensitiveFilter::build() {
std::queue<int> q;
for (auto [ch, to] : trie[0].next) {
trie[to].fail = 0;
q.push(to);
}
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto [ch, v] : trie[u].next) {
int f = trie[u].fail;
while (f && !trie[f].next.count(ch))
f = trie[f].fail;
if (trie[f].next.count(ch))
trie[v].fail = trie[f].next[ch];
q.push(v);
}
}
}
} // namespace Cubed

View File

@@ -5,13 +5,16 @@
namespace Cubed {
Button::Button(Widget* parent) : Widget(parent) {
m_background = std::make_unique<Image>(this);
m_background->set_fill(true);
m_background->set_fill_parent(true);
m_background->set_anchor(Anchor::TOP_LEFT);
m_foreground = std::make_unique<Label>(this);
m_foreground->set_anchor(Anchor::CENTER);
m_width = NORMAL_BUTTON_WIDTH;
m_height = NORMAL_BUTTON_HEIGHT;
}
void Button::on_update(float dt) {
Widget::on_update(dt);
if (m_background) {
m_background->update(dt);
}
@@ -27,6 +30,7 @@ void Button::on_render(Renderer& renderer) {
if (m_foreground) {
m_foreground->render(renderer);
}
Widget::on_render(renderer);
}
bool Button::handle_mouse_move_event(const MouseMoveEvent& e) {
@@ -62,8 +66,20 @@ Button& Button::set_scale(float scale) {
float Button::scale() const { return m_scale; }
float Button::width() const { return m_width * m_scale; }
float Button::height() const { return m_height * m_scale; }
float Button::width() const {
if (m_fill_width || m_fill_parent) {
return m_width;
}
return m_width * m_scale;
}
float Button::height() const {
if (m_fill_width || m_fill_parent) {
return m_width;
}
return m_height * m_scale;
}
Button& Button::set_width(float width) {
m_width = width;
update_text_scale();

200
src/ui/chat_box.cpp Normal file
View File

@@ -0,0 +1,200 @@
#include "Cubed/ui/chat_box.hpp"
#include "Cubed/tools/font.hpp"
#include "Cubed/tools/time_tools.hpp"
#include <utf8cpp/utf8.h>
namespace Cubed {
ChatBox::ChatBox(Widget* parent) : Widget(parent) {}
void ChatBox::add_message(ChatMessage& message) {
while (m_messages.size() > MAX_MESSGAES_SUM) {
m_messages.pop_front();
}
std::string str = message.system_msg
? std::format("{}", message.text)
: std::format("<{}>{}", message.player, message.text);
auto split_str = wrap_message(str);
for (auto it = split_str.begin(); it != split_str.end(); ++it) {
auto lable = std::make_unique<Label>(this);
lable->set_text(*it).set_scale(m_text_scale).set_color(message.color);
auto background = std::make_unique<Rect>(lable.get());
background->set_fill_height(true);
background->set_anchor(Anchor::TOP_LEFT);
background->set_alpha(0.6f)
.set_color(Color::GRAY)
.set_width(text_label_width());
lable->set_background(std::move(background))
.set_anchor(Anchor::TOP_LEFT);
m_messages.emplace_back(std::move(lable), message.time);
}
}
ChatBox& ChatBox::set_scale(float scale) {
m_scale = scale;
if (m_text_field) {
m_text_field->set_scale(scale);
}
return *this;
}
ChatBox& ChatBox::set_text_scale(float scale) {
m_text_scale = scale;
for (auto& text : m_messages) {
text.label->set_scale(scale);
}
return *this;
}
ChatBox& ChatBox::set_show_lines(int lines) {
m_lines = lines;
return *this;
}
ChatBox& ChatBox::set_spacing(float spacing) {
m_spacing = spacing;
return *this;
}
ChatBox& ChatBox::clear_input() {
m_text_field->clear_input();
return *this;
}
std::string& ChatBox::get_input_text() { return m_text_field->input_text(); }
float ChatBox::width() const {
if (m_fill_width || m_fill_parent) {
return m_width;
}
return m_width * m_scale;
}
float ChatBox::height() const {
// Height is dynamically calculated, no scaling needed
return m_height;
}
float ChatBox::text_label_width() const { return m_text_width * m_scale; }
void ChatBox::set_text_field(std::unique_ptr<TextField> text_field) {
m_text_field = std::move(text_field);
}
void ChatBox::set_typing(bool typing, bool finished) {
if (m_text_field) {
m_text_field->set_typing(typing, finished);
m_text_field->set_visible(typing);
}
}
void ChatBox::layout() {
int y;
if (m_text_field) {
y = m_text_field->height() + m_spacing;
} else {
y = m_spacing;
}
int line = 0;
// Shift upward sequentially starting from the latest
for (auto it = m_messages.rbegin(); it != m_messages.rend(); ++it) {
if (!it->label) {
continue;
}
if (line > m_lines) {
it->render = false;
continue;
}
++line;
it->label->set_anchor(Anchor::BOTTOM_LEFT);
// -y means upward offset
it->label->set_offset({0, -y});
y += it->label->height() + m_spacing;
}
m_height = m_lines == 0 ? 0 : (y - m_spacing);
}
void ChatBox::on_update(float dt) {
Widget::on_update(dt);
auto tick = Tools::get_time_ticks();
for (auto& m : m_messages) {
m.label->update(dt);
if (!m.render) {
continue;
}
if (tick < m.time) {
Logger::error("Tick {} Less Than Line Time {}", tick, m.time);
continue;
}
auto elapsed = tick - m.time;
if (elapsed >= DISAPPEAR_TIME * 1000) {
m.render = false;
}
}
layout();
m_text_field->update(dt);
}
void ChatBox::on_render(Renderer& renderer) {
if (m_text_field) {
m_text_field->render(renderer);
}
for (auto it = m_messages.rbegin(); it != m_messages.rend(); ++it) {
if (!it->label) {
continue;
}
if (m_text_field->is_typing() || it->render) {
it->label->render(renderer);
}
}
Widget::on_render(renderer);
}
bool ChatBox::handle_text_input_event(const TextInputEvent& e) {
if (m_text_field && m_text_field->handle_text_input_event(e)) {
return true;
}
return Widget::handle_text_input_event(e);
}
bool ChatBox::handle_key_event(const KeyEvent& e) {
if (m_text_field->handle_key_event(e)) {
return true;
}
return Widget::handle_key_event(e);
}
std::vector<std::string> ChatBox::wrap_message(const std::string& text) const {
std::vector<std::string> lines;
std::string line;
size_t last_space = std::string::npos;
auto it = text.begin();
while (it != text.end()) {
auto begin = it;
utf8::next(it, text.end());
line.append(begin, it);
if (*begin == ' ')
last_space = line.size() - 1;
if (Font::text_width(line) * m_text_scale > text_label_width()) {
if (last_space != std::string::npos) {
lines.emplace_back(line.substr(0, last_space));
line.erase(0, last_space + 1);
last_space = std::string::npos;
} else {
line.erase(line.size() - (it - begin));
lines.emplace_back(line);
line.assign(begin, it);
}
}
}
if (!line.empty())
lines.emplace_back(std::move(line));
return lines;
}
} // namespace Cubed

View File

@@ -7,8 +7,8 @@ ColumnLayout::ColumnLayout(Widget* parent) : Widget(parent) {
ColumnLayout::~ColumnLayout() {}
void ColumnLayout::update(float dt) {
layout();
Widget::update(dt);
layout();
}
float ColumnLayout::width() const { return m_content_width; }

View File

@@ -16,14 +16,15 @@ void CreditsUI::init() {
auto& renderer = m_scene.scene_manager().app().renderer();
auto image = std::make_unique<Image>(nullptr);
image->set_fill(true)
.set_image("texture/ui/background.png",
m_scene.scene_manager().app().texture_manager())
image
->set_image("texture/ui/background.png",
m_scene.scene_manager().app().texture_manager())
.set_anchor(Anchor::TOP_LEFT)
.set_window_size(renderer.window_width(), renderer.window_height());
.set_window_size(renderer.window_width(), renderer.window_height())
.set_fill_parent(true);
auto& rect = image->add_child<Rect>();
rect.set_fill(true).set_color(Color::BLACK).set_alpha(0.7f);
rect.set_color(Color::BLACK).set_alpha(0.7f).set_fill_parent(true);
{
auto& button = rect.add_child<Button>();
@@ -47,22 +48,23 @@ void CreditsUI::init() {
add_text("A cube game like Minecraft, using C++ and OpenGL.");
add_text("Author: zhenyan121");
add_text("Libraries Used", 0.8f);
add_text("glad");
add_text("GLFW");
add_text("SDL3");
add_text("SOIL2");
add_text("GLM");
add_text("FreeType");
add_text("toml++");
add_text("Dear ImGui");
add_text("Tbb");
add_text("Asio");
add_text("protobuf");
add_text("zstd");
add_text("OpenAl Soft");
add_text("dr_libs");
add_text("nlohmann/json");
add_text("HarfBuzz");
add_text("GLAD MIT / Apache-2.0");
add_text("SDL3 zlib");
add_text("SOIL2 MIT-0");
add_text("GLM MIT");
add_text("FreeType FTL / GPL-2.0+");
add_text("toml++ MIT");
add_text("Dear ImGui MIT");
add_text("Tbb Apache-2.0");
add_text("Asio BSL-1.0");
add_text("protobuf BSD-3-Clause");
add_text("zstd BSD-3-Clause / GPL-2.0");
add_text("OpenAL Soft LGPL-2.1+");
add_text("Opus BSD-3-Clause");
add_text("dr_libs MIT-0 / Unlicense");
add_text("nlohmann/json MIT");
add_text("HarfBuzz Old-MIT / GPL-2.0+");
add_text("utf8cpp BSL-1.0");
add_text("Music", 0.8f);
add_text("'Find a Peaceful Place' by ROZKOL (Free Music Archive), CC "
"BY 4.0.");

View File

@@ -16,10 +16,10 @@ void ErrorUI::init() {
bi->set_window_size(renderer.window_width(), renderer.window_height());
bi->set_anchor(Anchor::TOP_LEFT);
bi->set_image("texture/ui/background.png", texture_manager);
bi->set_fill(true);
bi->set_fill_parent(true);
auto& rect = bi->add_child<Rect>();
rect.set_fill(true);
rect.set_fill_parent(true);
rect.set_alpha(0.7f);
rect.set_color(Color::BLACK);

View File

@@ -6,6 +6,7 @@
#include "Cubed/scene/scene_manager.hpp"
#include "Cubed/ui/button.hpp"
#include "Cubed/ui/column_layout.hpp"
#include "Cubed/ui/default_image.hpp"
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/text_field.hpp"
namespace Cubed {
@@ -18,10 +19,10 @@ void HostGameUI::init() {
bi->set_window_size(renderer.window_width(), renderer.window_height());
bi->set_anchor(Anchor::TOP_LEFT);
bi->set_image("texture/ui/background.png", texture_manager);
bi->set_fill(true);
bi->set_fill_parent(true);
auto& rect = bi->add_child<Rect>();
rect.set_fill(true);
rect.set_fill_parent(true);
rect.set_alpha(0.7f);
rect.set_color(Color::BLACK);
@@ -48,7 +49,10 @@ void HostGameUI::init() {
auto& text_seed = layout.add_child<TextField>();
text_seed.set_show_text(tr("hostgame.world_seed"));
text_seed.set_app(&m_scene.scene_manager().app());
text_seed.set_default_image(texture_manager);
std::unique_ptr<Image> back = std::make_unique<Image>(&text_seed);
back->set_image(DEFAULT_TEXT_FIELD_IMAGE, texture_manager)
.set_fill_parent(true);
text_seed.set_background(std::move(back));
text_seed.set_on_finish([this, &text_seed]() {
unsigned seed = 0;
auto& text = text_seed.input_text();
@@ -67,7 +71,10 @@ void HostGameUI::init() {
}
{
auto& text_port = layout.add_child<TextField>();
text_port.set_default_image(texture_manager);
std::unique_ptr<Image> back = std::make_unique<Image>(&text_port);
back->set_image(DEFAULT_TEXT_FIELD_IMAGE, texture_manager)
.set_fill_parent(true);
text_port.set_background(std::move(back));
text_port.set_show_text(tr("hostgame.port"));
text_port.set_app(&m_scene.scene_manager().app());
text_port.set_on_finish([this, &text_port]() {

View File

@@ -6,20 +6,11 @@
namespace Cubed {
Image::Image(Widget* parent) : Widget(parent) {}
void Image::on_render(Renderer& renderer) { renderer.render_image(*this); }
void Image::on_update(float) {
if (m_fill) {
if (m_fill) {
if (!m_parent) {
m_width = m_window_width;
m_height = m_window_height;
} else {
m_width = m_parent->width();
m_height = m_parent->height();
}
}
}
void Image::on_render(Renderer& renderer) {
renderer.render_image(*this);
Widget::on_render(renderer);
}
void Image::on_update(float dt) { Widget::on_update(dt); }
Image& Image::set_image(const std::string& path,
TextureManager& texture_manager) {
m_texture = texture_manager.get_image_texture(path);
@@ -37,6 +28,9 @@ float Image::height() const {
Logger::error("Image not set image!");
return 0.0f;
}
if (m_fill_height || m_fill_parent) {
return m_height;
}
return m_height * m_scale;
}
@@ -45,23 +39,12 @@ float Image::width() const {
Logger::error("Image not set image!");
return 0.0f;
}
if (m_fill_parent || m_fill_width) {
return m_width;
}
return m_width * m_scale;
}
Image& Image::set_height(float height) {
m_height = height;
return *this;
}
Image& Image ::set_width(float width) {
m_width = width;
return *this;
}
Image& Image::set_fill(bool fill) {
m_fill = fill;
return *this;
}
const Texture* Image::texture() const { return m_texture; }
} // namespace Cubed

View File

@@ -5,6 +5,7 @@
#include "Cubed/scene/join_game_scene.hpp"
#include "Cubed/ui/button.hpp"
#include "Cubed/ui/column_layout.hpp"
#include "Cubed/ui/default_image.hpp"
#include "Cubed/ui/text_field.hpp"
namespace Cubed {
JoinGameUI::JoinGameUI(JoinGameScene& scene) : m_scene(scene) {}
@@ -16,10 +17,10 @@ void JoinGameUI::init() {
bi->set_window_size(renderer.window_width(), renderer.window_height());
bi->set_anchor(Anchor::TOP_LEFT);
bi->set_image("texture/ui/background.png", texture_manager);
bi->set_fill(true);
bi->set_fill_parent(true);
auto& rect = bi->add_child<Rect>();
rect.set_fill(true);
rect.set_fill_parent(true);
rect.set_alpha(0.7f);
rect.set_color(Color::BLACK);
@@ -45,7 +46,10 @@ void JoinGameUI::init() {
{
auto& text_ip = layout.add_child<TextField>();
text_ip.set_show_text(tr("joingame.server_ip"));
text_ip.set_default_image(texture_manager);
std::unique_ptr<Image> back = std::make_unique<Image>(&text_ip);
back->set_image(DEFAULT_TEXT_FIELD_IMAGE, texture_manager)
.set_fill_parent(true);
text_ip.set_background(std::move(back));
text_ip.set_app(&m_scene.scene_manager().app());
text_ip.set_on_finish([this, &text_ip]() {
auto& ip = text_ip.input_text();

View File

@@ -9,7 +9,6 @@ Label& Label::set_text(std::string_view text) {
update_vertices();
return *this;
}
Label& Label::set_color(Color color) {
m_text.color = color;
return *this;
@@ -19,9 +18,26 @@ Label& Label::set_scale(float scale) {
return *this;
}
void Label::on_update(float dt) { (void)dt; }
Label& Label::set_background(std::unique_ptr<Widget> background) {
m_background = std::move(background);
return *this;
}
Widget* Label::get_background() { return m_background.get(); }
void Label::on_update(float dt) {
Widget::on_update(dt);
if (m_background) {
m_background->update(dt);
}
}
void Label::on_render(Renderer& renderer) { renderer.render_lable(*this); }
void Label::on_render(Renderer& renderer) {
if (m_background) {
m_background->render(renderer);
}
renderer.render_lable(*this);
Widget::on_render(renderer);
}
void Label::update_vertices() {
auto textmesh = Font::get().vertices(m_text.text);
@@ -29,8 +45,8 @@ void Label::update_vertices() {
m_offset_x = textmesh.min_x;
m_offset_y = textmesh.min_y;
m_real_width = textmesh.width;
m_real_height = textmesh.height;
m_width = m_real_width = textmesh.width;
m_height = m_real_height = textmesh.height;
m_data.update_sum();
m_data.upload();
@@ -38,8 +54,21 @@ void Label::update_vertices() {
const UIVertexData& Label::data() const { return m_data; }
const TextStyle& Label::text_style() const { return m_text; }
float Label::width() const { return m_real_width * m_scale; }
float Label::height() const { return m_real_height * m_scale; }
float Label::width() const {
if (m_fill_width || m_fill_parent) {
return m_width;
}
return m_width * m_scale;
}
float Label::height() const {
if (m_fill_height || m_fill_parent) {
return m_height;
}
return m_height * m_scale;
}
float Label::real_width() const { return m_real_width; }
float Label::real_height() const { return m_real_height; }
float Label::offset_x() const { return m_offset_x; }

View File

@@ -18,7 +18,7 @@ void MainMenuUIManager::init() {
auto image = std::make_unique<Image>(nullptr);
auto& texture_manager = m_scene.scene_manager().app().texture_manager();
image->set_fill(true);
image->set_fill_parent(true);
image->set_anchor(Anchor::TOP_LEFT);
image->set_image("texture/ui/background.png", texture_manager);
auto& renderer = m_scene.scene_manager().app().renderer();

View File

@@ -12,7 +12,7 @@ PauseMenuUIManager::PauseMenuUIManager(WorldScene& scene) : m_scene(scene) {}
void PauseMenuUIManager::init() {
auto rect = std::make_unique<Rect>(nullptr);
rect->set_fill(true);
rect->set_fill_parent(true);
rect->set_color(Color::BLACK);
rect->set_alpha(0.5f);
rect->set_anchor(Anchor::TOP_LEFT);

View File

@@ -12,35 +12,27 @@ Rect::Rect(Widget* parent)
Rect::~Rect() {}
void Rect::on_update(float) {
if (m_fill) {
if (!m_parent) {
m_width = m_window_width;
m_height = m_window_height;
} else {
m_width = m_parent->width();
m_height = m_parent->height();
}
void Rect::on_update(float dt) { Widget::on_update(dt); }
void Rect::on_render(Renderer& renderer) {
renderer.render_rect(*this);
Widget::on_render(renderer);
}
float Rect::width() const {
if (m_fill_width || m_fill_parent) {
return m_width;
}
return m_width * m_scale;
}
void Rect::on_render(Renderer& renderer) { renderer.render_rect(*this); }
float Rect::height() const {
float Rect::width() const { return m_width * m_scale; }
float Rect::height() const { return m_height * m_scale; }
if (m_fill_height || m_fill_parent) {
return m_height;
}
return m_height * m_scale;
}
float Rect::alpha() const { return m_alpha; }
Rect& Rect::set_width(float width) {
m_width = width;
return *this;
}
Rect& Rect::set_height(float height) {
m_height = height;
return *this;
}
Rect& Rect::set_fill(bool fill) {
m_fill = fill;
return *this;
}
Rect& Rect::set_scale(float scale) {
m_scale = scale;

View File

@@ -21,10 +21,10 @@ void SettingsUI::init() {
bi->set_window_size(renderer.window_width(), renderer.window_height());
bi->set_anchor(Anchor::TOP_LEFT);
bi->set_image("texture/ui/background.png", texture_manager);
bi->set_fill(true);
bi->set_fill_parent(true);
auto& rect = bi->add_child<Rect>();
rect.set_fill(true);
rect.set_fill_parent(true);
rect.set_alpha(0.7f);
rect.set_color(Color::BLACK);
@@ -69,15 +69,41 @@ void SettingsUI::init() {
sfx.set_slider(&v.sfx, 0.0f, 1.0f);
set_default_slider_image(sfx);
sfx.set_slider_text("settings.sfx_volume", "sfx");
auto& player_voice = layout.add_child<Slider>();
player_voice.set_slider(&v.player_voice, 0.0f, 1.0f);
set_default_slider_image(player_voice);
player_voice.set_slider_text("settings.player_voice", "volume");
}
auto& config = m_scene.scene_manager().app().config();
{
auto& combo = layout.add_child<ComboButton>();
auto type = config.get("voice_input", "PTT");
if (type == "off") {
combo.set_index(0);
} else if (type == "PTT") {
combo.set_index(1);
} else if (type == "always") {
combo.set_index(2);
}
combo.set_combo_text("settings.voice_input", "type");
std::vector<ComboPair> comb;
comb.emplace_back(tr("common.off"),
[&config]() { config.set("voice_input", "off"); });
comb.emplace_back(tr("voice_input.ptt"),
[&config]() { config.set("voice_input", "PTT"); });
comb.emplace_back(tr("voice_input.always"),
[&config]() { config.set("voice_input", "always"); });
combo.set_default_image(texture_manager);
combo.set_combos(comb);
}
{
bool full = config.get("window.fullscreen", false);
auto& fullscreen = layout.add_child<ComboButton>();
fullscreen.set_index(!full ? 0 : 1);
fullscreen.set_combo_text("settings.fullscreen", "state");
std::vector<std::pair<std::string, std::function<void()>>> comb;
std::vector<ComboPair> comb;
comb.emplace_back(tr("common.off"), [&config, this]() {
config.set("window.fullscreen", false);
m_scene.scene_manager().app().window().reload_config();

View File

@@ -13,6 +13,8 @@ Slider::Slider(Widget* parent) : Widget(parent) {
m_label = std::make_unique<Label>(this);
m_label->set_anchor(Anchor::CENTER);
m_width = NORMAL_SLIDER_WIDTH;
m_height = NORMAL_SLIDER_HEIGHT;
update_text_scale();
}
@@ -37,7 +39,7 @@ Slider& Slider::set_slider(int* value, const int& min, const int& max) {
void Slider::init_track() {
m_track = std::make_unique<Image>(this);
m_track->set_fill(true);
m_track->set_fill_parent(true);
m_track->set_anchor(Anchor::TOP_LEFT);
}
@@ -54,8 +56,20 @@ void Slider::init_thumb() {
m_thumb->set_scale(m_scale);
}
float Slider::width() const { return m_width * m_scale; }
float Slider::height() const { return m_height * m_scale; }
float Slider::width() const {
if (m_fill_width || m_fill_parent) {
return m_width;
}
return m_width * m_scale;
}
float Slider::height() const {
if (m_fill_height || m_fill_parent) {
return m_height;
}
return m_height * m_scale;
}
Slider& Slider::set_scale(float scale) {
m_scale = scale;
@@ -160,6 +174,7 @@ void Slider::update_value(float mouse_x) {
}
void Slider::on_update(float dt) {
Widget::on_update(dt);
if (!m_thumb || !m_track) {
Logger::error("Please Set value and thumb and track");
ASSERT(false);
@@ -216,6 +231,7 @@ void Slider::on_render(Renderer& renderer) {
if (m_label) {
m_label->render(renderer);
}
Widget::on_render(renderer);
}
void Slider::update_text_scale() {

View File

@@ -11,11 +11,8 @@ constexpr float DELTA_CUROUR_HEIGHT = 10.0f;
namespace Cubed {
TextField::TextField(Widget* parent) : Widget(parent) {
m_background = std::make_unique<Image>(this);
m_background->set_fill(true);
m_background->set_anchor(Anchor::TOP_LEFT);
m_width = NORMAL_TEXTFIELD_WIDTH;
m_height = NORMAL_TEXTFIELD_HEIGHT;
m_foreground = std::make_unique<Label>(this);
m_foreground->set_anchor(Anchor::CENTER_LEFT);
m_foreground->set_offset({10, 0});
@@ -26,6 +23,7 @@ TextField::TextField(Widget* parent) : Widget(parent) {
m_cursor->set_anchor(Anchor::CENTER_LEFT);
m_cursor->set_offset({10, 0});
m_cursor->set_color(Color::WHITE);
update_text_scale();
}
@@ -62,6 +60,9 @@ void TextField::on_render(Renderer& renderer) {
}
}
void TextField::on_update(float dt) {
Widget::on_update(dt);
m_cursor_timer += dt;
if (m_cursor_timer >= CURSOR_INTERVAL) {
m_cursor_timer = 0.0f;
@@ -79,18 +80,15 @@ void TextField::on_update(float dt) {
}
void TextField::update_show_text() {
if (m_input_text.empty()) {
if (!m_typing) {
m_foreground->set_text(m_show_text);
m_foreground->set_color(Color::GRAY);
} else {
m_foreground->set_text(" ");
}
if (!m_typing && m_input_text.empty()) {
m_foreground->set_text(m_show_text);
m_foreground->set_color(Color::GRAY);
} else {
m_foreground->set_text(m_input_text);
m_foreground->set_color(Color::WHITE);
}
update_text_scale();
update_input_area();
m_cursor->set_offset({13.0f + m_foreground->width(), 0.0f});
@@ -108,11 +106,24 @@ void TextField::update_input_area() {
TextField& TextField::set_scale(float scale) {
m_scale = scale;
m_cursor->set_height(std::max(1.0f, height() - DELTA_CUROUR_HEIGHT));
return *this;
}
float TextField::width() const { return m_width * m_scale; }
float TextField::height() const { return m_height * m_scale; }
float TextField::width() const {
if (m_fill_width) {
return m_width;
}
return m_width * m_scale;
}
float TextField::height() const {
if (m_fill_height) {
return m_height;
}
return m_height * m_scale;
}
TextField& TextField::set_width(float width) {
m_width = width;
@@ -130,14 +141,10 @@ TextField& TextField::set_show_text(const std::string& text) {
update_show_text();
return *this;
}
TextField& TextField::set_background_image(const std::string& path,
TextureManager& texture_manager) {
m_background->set_image(path, texture_manager);
return *this;
}
TextField& TextField::set_default_image(TextureManager& texture_manager) {
return set_background_image(DEFAULT_TEXT_FIELD_IMAGE, texture_manager);
TextField& TextField::set_background(std::unique_ptr<Widget> background) {
m_background = std::move(background);
return *this;
}
TextField& TextField::set_auto_scale(bool auto_scale) {
@@ -149,8 +156,41 @@ TextField& TextField::set_app(App* app) {
m_app = app;
return *this;
}
const std::string& TextField::input_text() const { return m_input_text; }
TextField& TextField::set_typing(bool typing, bool finished) {
m_typing = typing;
if (m_typing) {
start_typing();
} else {
stop_typing(finished);
}
return *this;
}
TextField& TextField::clear_input() {
m_input_text.clear();
update_show_text();
return *this;
}
bool TextField::is_typing() const { return m_typing; }
void TextField::start_typing() {
if (m_app) {
m_app->start_text_input();
}
update_show_text();
}
void TextField::stop_typing(bool finished) {
if (m_app) {
m_app->stop_text_input();
}
if (m_on_finished && finished) {
m_on_finished();
}
}
const std::string& TextField::input_text() const { return m_input_text; }
std::string& TextField::input_text() { return m_input_text; }
bool TextField::handle_mouse_move_event(const MouseMoveEvent& e) {
auto p = pos();
if (e.xpos >= p.x && e.xpos <= p.x + width() && e.ypos >= p.y &&
@@ -166,20 +206,12 @@ bool TextField::handle_mouse_button_event(const MouseButtonEvent& e) {
if (e.key == MouseKey::LEFT_BUTTON && e.action == KeyAction::PRESS) {
if (m_inside) {
m_typing = true;
if (m_app) {
m_app->start_text_input();
}
update_show_text();
start_typing();
return false;
} else {
if (m_typing) {
m_typing = false;
if (m_app) {
m_app->stop_text_input();
}
if (m_on_finished) {
m_on_finished();
}
stop_typing(true);
return false;
}
@@ -188,6 +220,7 @@ bool TextField::handle_mouse_button_event(const MouseButtonEvent& e) {
return false;
}
bool TextField::handle_text_input_event(const TextInputEvent& e) {
if (m_typing) {
m_input_text.append(e.text);
update_show_text();
@@ -199,12 +232,7 @@ bool TextField::handle_key_event(const KeyEvent& e) {
if (e.key == Key::ENTER && e.action == KeyAction::PRESS) {
if (m_typing) {
m_typing = false;
if (m_app) {
m_app->stop_text_input();
}
if (m_on_finished) {
m_on_finished();
}
stop_typing(true);
return true;
}
@@ -227,6 +255,12 @@ bool TextField::handle_key_event(const KeyEvent& e) {
}
}
if (e.key == Key::ESCAPE && e.action == KeyAction::PRESS) {
stop_typing(false);
clear_input();
return true;
}
if (e.key == Key::V && e.action == KeyAction::PRESS && m_ctrl_press) {
if (m_app && m_typing) {
m_input_text.append(m_app->get_clipboard_text());

View File

@@ -1,8 +1,5 @@
#include "Cubed/ui/ui_vertex_data.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
namespace Cubed {
UIVertexData::UIVertexData() {}
UIVertexData::~UIVertexData() {
@@ -12,8 +9,7 @@ UIVertexData::~UIVertexData() {
void UIVertexData::upload() {
if (m_sum == 0) {
Logger::error("You need update_sum first");
ASSERT(false);
return;
}
if (m_vertices.size() == 0) {
return;

View File

@@ -3,7 +3,12 @@
#include "Cubed/tools/log.hpp"
namespace Cubed {
Widget::Widget(Widget* parent) : m_parent(parent) {}
Widget::Widget(Widget* parent) : m_parent(parent) {
if (!m_parent) {
// The root node of the window automatically fills the entire window.
set_fill_parent(true);
}
}
void Widget::update(float dt) {
on_update(dt);
@@ -23,7 +28,19 @@ void Widget::render(Renderer& renderer) {
}
}
void Widget::on_update(float) {}
void Widget::on_update(float) {
if (m_fill_width) {
m_width = m_parent ? m_parent->width() : m_window_width;
}
if (m_fill_height) {
m_height = m_parent ? m_parent->height() : m_window_height;
}
if (m_fill_parent) {
m_width = m_parent ? m_parent->width() : m_window_width;
m_height = m_parent ? m_parent->height() : m_window_height;
}
}
void Widget::on_render(Renderer&) {}
std::vector<std::unique_ptr<Widget>>& Widget::children() { return m_children; }
@@ -111,17 +128,29 @@ Widget& Widget::set_visible(bool visible) {
return *this;
}
float Widget::width() const {
if (m_parent) {
return m_parent->width();
}
return m_window_width;
float Widget::width() const { return m_width; }
float Widget::height() const { return m_height; }
Widget& Widget::set_width(float width) {
m_width = width;
return *this;
}
float Widget::height() const {
if (m_parent) {
return m_parent->height();
}
return m_window_height;
Widget& Widget::set_height(float height) {
m_height = height;
return *this;
}
Widget& Widget::set_fill_parent(bool fill) {
m_fill_parent = fill;
return *this;
}
Widget& Widget::set_fill_width(bool fill) {
m_fill_width = fill;
return *this;
}
Widget& Widget::set_fill_height(bool fill) {
m_fill_height = fill;
return *this;
}
glm::vec2 Widget::pos() const { return compute_position(); }

View File

@@ -2,26 +2,74 @@
#include "Cubed/app.hpp"
#include "Cubed/debug_collector.hpp"
#include "Cubed/gameplay/client_world.hpp"
#include "Cubed/localization.hpp"
#include "Cubed/render/renderer.hpp"
#include "Cubed/scene/scene_manager.hpp"
#include "Cubed/scene/world_scene.hpp"
#include "Cubed/ui/chat_box.hpp"
namespace Cubed {
WorldUIManager::WorldUIManager(WorldScene& scene) : m_scene(scene) {}
WorldUIManager::~WorldUIManager() {}
void WorldUIManager::init() {
auto crosshair = std::make_unique<Image>(nullptr);
crosshair->set_image("texture/ui/0.png",
m_scene.scene_manager().app().texture_manager());
m_root_widget = std::make_unique<Widget>(nullptr);
m_root_widget->set_fill_parent(true);
auto& renderer = m_scene.scene_manager().app().renderer();
crosshair->set_window_size(renderer.window_width(),
renderer.window_height());
crosshair->set_anchor(Anchor::CENTER);
crosshair->set_scale(3.0f);
m_widgets.try_emplace("crosshair", crosshair.get());
m_root_widget = std::move(crosshair);
m_root_widget->set_window_size(renderer.window_width(),
renderer.window_height());
auto& texture_manager = m_scene.scene_manager().app().texture_manager();
auto& crosshair = m_root_widget->add_child<Image>();
crosshair.set_image("texture/ui/0.png", texture_manager);
crosshair.set_anchor(Anchor::CENTER);
crosshair.set_scale(3.0f);
m_widgets.try_emplace("crosshair", &crosshair);
auto& chat_box = m_root_widget->add_child<ChatBox>();
auto text_field = std::make_unique<TextField>(&chat_box);
text_field->set_anchor(Anchor::BOTTOM_LEFT);
auto rect = std::make_unique<Rect>(text_field.get());
rect->set_color(Color::GRAY).set_alpha(0.6f).set_fill_parent(true);
text_field->set_background(std::move(rect))
.set_app(&m_scene.scene_manager().app())
.set_fill_width(true)
.set_visible(false)
.set_height(15.0f);
chat_box.set_text_field(std::move(text_field));
chat_box.set_spacing(0);
chat_box.set_anchor(Anchor::BOTTOM_LEFT);
chat_box.set_offset({0, -10});
// chat_box.set_width(500);
chat_box.set_fill_width(true);
// chat_box.set_scale(2.0f);
chat_box.set_text_scale(0.6f);
chat_box.set_on_finish([this, &chat_box]() {
ChatMessage message{m_scene.client_world().get_player().get_name(),
std::move(chat_box.get_input_text()), Color::WHITE,
false, 0};
chat_box.clear_input();
m_scene.client_world().send_chat_message(message);
});
m_chat_box = &chat_box;
auto& microphone = m_root_widget->add_child<Image>();
microphone.set_image("texture/ui/microphone.png", texture_manager)
.set_scale(5.0f)
.set_anchor(Anchor::BOTTOM_RIGHT)
.set_visible(false);
m_mircophone = &microphone;
auto& disbale_voice = m_root_widget->add_child<Label>();
disbale_voice.set_scale(0.6f);
disbale_voice.set_text(tr("error.disable_voice"))
.set_color(Color::RED)
.set_offset({0, -5});
disbale_voice.set_anchor(Anchor::BOTTOM_RIGHT).set_visible(false);
m_disbable_voice = &disbale_voice;
}
void WorldUIManager::render(Renderer& renderer) {
renderer.begin_render_ui();
@@ -29,7 +77,38 @@ void WorldUIManager::render(Renderer& renderer) {
auto& widget = DebugCollector::get().get_widget();
widget.render(renderer);
m_root_widget->render(renderer);
renderer.end_render_ui();
}
void WorldUIManager::update(float dt) {
UIManager::update(dt);
if (m_scene.is_recording()) {
if (m_scene.client_world().enable_voice_chat()) {
m_mircophone->set_visible(true);
} else {
m_disbable_voice->set_visible(true);
}
} else {
m_mircophone->set_visible(false);
m_disbable_voice->set_visible(false);
}
}
void WorldUIManager::set_chatting(bool chantting, bool send) {
m_chat_box->set_typing(chantting, send);
}
void WorldUIManager::add_chat_message(ChatMessage& message) {
m_chat_box->add_message(message);
}
bool WorldUIManager::handle_key_event(const KeyEvent& e) {
return UIManager::handle_key_event(e);
}
} // namespace Cubed

View File

@@ -5,6 +5,7 @@
"openal-soft",
"harfbuzz",
"freetype",
"opus",
{
"name": "sdl3",
"default-features": false