mirror of
https://github.com/zhenyan121/Cubed.git
synced 2026-08-08 17:57:02 +08:00
* build(deps): add assimp library as dependency * feat(render): add model loading and rendering pipeline * refactor(render): rename depth player shaders to depth model and clean up * build: add EnTT library * feat(entity): add ECS-based entity rendering * feat(render): add shadow pass for entity models * refactor(render): unify model and player rendering with single shader pipeline * refactor(collision): convert AABB to center-half representation and migrate player data to ECS * refactor(gameplay): add base classes Chunk and World for shared logic * feat(gameplay): implement entity movement system with collision detection - Add Velocity and HitBoxes components to entity - Introduce HitboxManager for loading per-entity collision AABBs from JSON - Create MoveSystem with per-axis collision handling - Move get_block_aabb to base World class and add virtual get_per_tick_time - Remove static get_block_aabb from ClientWorld; use member m_per_tick_time for tick duration * fix(gameplay): correct hitbox insertion in HitboxManager::load * build: remove entt library * refactor(gameplay): replace entt components with SparseVector for player data Refactor client world to use a custom SparseVector for player data instead of entt registry. Consolidate Transform, ViewAngles, and related structs into Position, Orientation, WalkPose. Introduce PlayerData and PlayerRenderData. Remove the unused move_system.cpp. Unify player render and shadow render into a single function. * feat(render): add model ID system with concurrent lookup and namespace-based loading - Extract `ModelID` and `Model` struct to new `model.hpp` - Replace `std::unordered_map` with `tbb::concurrent_hash_map` for thread safety - Add `get_model(ModelID)`, `get_model_id`, `get_model_name` methods - Parse model names in `namespace:name` format to construct asset paths - Update `load_model` to accept `string_view` and use ID-based management * refactor(gameplay): extract movement, gravity, orientation, and walk pose into structs * refactor(gameplay): extract Entity base class from ClientPlayer Move position, walk pose, velocity, orientation, movement, and gravity fields and their accessors into a new Entity base class. ClientPlayer now inherits from Entity, removing duplicated members. Also update velocity handling to use 3D vector per axis and adjust related logic. * feat(player): split max speed into horizontal/vertical, set spawn pos * refactor: move movement logic into SpeedSystem and Entity components * refactor(gameplay): extract physics and collision from ClientPlayer into PhysicalSystem Move per-axis collision detection and move distance calculation to new PhysicalSystem. Move SpeedSystem implementation from inline header to separate .cpp file. Add const accessors to Entity. Replace inline AABB helper with HitboxManager registration of player hitbox using new PLAYER_SIZE constant. Remove obsolete members and functions from ClientPlayer. * refactor(gameplay): integrate model and hitbox ID system into Entity - Introduce HitboxID, EntityID, and ModelID types for safer ID-based lookups - Replace AABB struct with Hitbox (includes HitboxID) - Convert ModelManager and HitboxManager to singletons with Handle structs - Update Entity to store IDs for model and hitbox, removing direct references - Reorganize creature model assets into subdirectories per entity type - Add player model (player.glb) and collision data for pig - Remove ModelManager dependency from App and Renderer - Add namespace parsing utility for asset paths - Mark sparse_vector::insert() with [[nodiscard]] * build: add entt library * refactor(gameplay): rename ClientPlayer to LocalPlayer * refactor(gameplay): separate player logic into manager and ECS components * feat(gameplay): add entity managers and refactor to ECS components * refactor(gameplay): replace client thread with timer-based system and add entity manager * feat(gameplay): implement entity system with concurrent task handling and fix model loading * feat(gameplay): add entity destruction support * feat(entity): add client-to-server entity creation and destruction requests Extend the network protocol with `C2SEntityCreateRequest` and `C2SEntityDestoryRequest` packets. Refactor entity managers to split public client-facing create/destroy methods that send requests over the network, from internal handlers that process received packets. Add utility functions for converting protobuf Vec3 to glm::vec3. * feat(gameplay): implement entity update packets Add S2CEntityUpdate to sync entity positions from server to client, including update handling in the client entity manager and server-side AI updates. * feat(ai): add wander AI system with move boost Add AIBase and WanderAITag components, a WanderAISystem, and a MoveBoost component to control wandering behavior. Replace the old MoveState with MoveBoost and include a horizontal random direction helper. * refactor(ecs): move entity physics to tick-based systems Update PhysicalSystem and SpeedSystem to operate on entt::registry instead of individual components. Add TickVelocity for server creatures so movement is calculated per tick without frame delta time. LocalPlayer now implements its own client-side physics with collision detection. * feat(gameplay): add server-side entity movement and AI Refactor LocalPlayer::update_physical to operate on a passed position, and run speed, physical, and wander AI systems in ServerEntityManager. * feat(gameplay): add pig wander AI and refine speed physics * feat(server): send entity position updates to all sessions * fix: correct velocity clamping and hitbox loading Preserve sign when clamping velocity; negative velocities now clamp to zero instead of flipping direction. Support loading hitbox definitions from JSON arrays and objects. Tune pig entity movement, spawn height, and wander probabilities. * feat(creatures): refine pig movement physics Add movement constants for pigs and switch deceleration to per-axis friction so creatures stop naturally. Extend wander boost duration for smoother behavior. * feat(physics): implement step-up for horizontal collisions * feat: sync entity direction and rotate models accordingly Move direction into the transform component and include it in server-to-client entity updates. Client now sets transform direction from the network message and uses it to compute yaw for model rotation, so entities visually face their movement direction. Refactor net_utils to support arbitrary Vec3 fields. * feat(render): interpolate entity transforms for rendering Add RenderTransform component to smooth position/direction updates and use it in entity and shadow passes. * fix(server_world): send time before entity updates * build: replace nlohmann json with rapidjson * refactor(json): migrate from nlohmann to rapidjson Replace nlohmann::json with rapidjson across localization, hitbox manager, server world, and sensitive filter. Add json_utils helper for converting rapidjson documents to maps, and improve parse error handling. * feat(item): add item manager with JSON asset loading Implement ItemManager to load and query item definitions from assets/item JSON files. Add ItemData struct, item asset metadata, CMake source registration, and initialize the manager during app startup. Also add AGENTS.md repository guidelines. * refactor(item): decouple items from block types The item system now supports an ItemKind and property, allowing item JSON to declare a type instead of assuming every item is a block. BlockManager was moved to its own header, redesigned around concurrent hash maps, and exposes id_from_name(). Texture and UI code now key items by ItemID, while block placement resolves the block type from the item registry. * fix(gameplay): use inline const for static EMPTY members Use inline const for static EMPTY members to avoid ODR and linker issues. Add missing block_manager.hpp includes in gameplay sources. * fix: stabilize block item registration and display Store item names as owned strings in ItemManager, set block type property for block items, validate item kind before placement, and handle items without textures gracefully in inventory UI. * feat: add pig spawn egg item Add pig spawn egg asset and texture, parse spawn egg item kind and creature property, and spawn the configured entity when used on an empty block. Also fix item texture loading to use actual image dimensions and update selected item UI sizing. * refactor(gameplay): update systems per entity with chunk check Refactor server entity update flow to process entities individually, skipping those whose chunk is not loaded. System update methods now accept a single entity instead of iterating the full registry view, and `ServerWorld::get_chunk_ref_count` is added to determine if an entity's chunk is active. * perf(render): skip entities outside loaded chunks * feat: add --direct-enter option to skip to world scene Support a new CLI flag that launches the app directly into the world scene. If no IP is provided, it starts a local server on the specified port and connects to 127.0.0.1; otherwise it connects to the given IP. With this flag enabled, a port must be specified via -p. Also expose SceneManager::push as public so scenes can be pushed immediately when bypassing the normal menu flow. * refactor(localization): switch block translations to item naming Remove the `name_key` field from block definitions and use item-based localization keys (`item.*.name`) for inventory display. Item data now stores the localized name at load time. * feat(gameplay): spawn creatures during chunk generation Add creature spawning to chunk generation with a configurable SpawnConfig, including a default pig spawn. Spawning occurs in the final generation phase and registers entities through the server world's entity manager. Also destroy entities when their chunk is unloaded to prevent orphaned entities and expose the entity manager from ServerWorld. * feat(gameplay): add run mode based thread pool config Introduce RunMode enum and thread pool sizing helpers for client, server, and hybrid modes. Add compute pool to server world and pass mode through server/client initialization. * perf(server): parallelize entity update loop Use parallel_do to process entities concurrently via the compute pool. Switch get_all_session to a thread-safe tbb::concurrent_vector and make ChunkEntity's ref_count atomic to avoid data races. Also remove the debug pig spawn from world init. * feat(creatures): animate creature walk cycles Add a Gait component synchronized over the network and procedural animation for model nodes. Load animation parameters from assets/model/creature/pig/animation.json and apply leg swing, body bob, and head motion based on gait. Refactor Gait into its own header for reuse. * fix(gameplay): make entity interpolation frame-rate independent * perf(render): batch model rendering with instancing Replaces per-entity draw calls with instanced rendering for both main and shadow passes. Each model's node hierarchy is flattened once and instance matrices are updated per frame, reducing draw calls and CPU overhead. * refactor(render): build entity instance buffers once per frame Move instance matrix upload into build_vertices and use a precomputed instance data map for both shadow and color passes, avoiding duplicate GPU buffer updates. * perf(gameplay): batch entity updates into single packet Aggregate per-entity update messages into S2CEntityUpdateBatch and broadcast once per tick. Reuse serialized packets in several broadcast loops to avoid repeated make_packet calls. * fix: correct thread count and shadow projection uniform - Add reserved client thread count to client threads in server generation calculation. - Set projection matrix uniform only for non-shadow rendering. * feat(ecs): add entity type separation and creature limits Replace generic entity creation with typed creatures and items. Rename `add_entity` to `add_creature`, enforce per-player creature cap, and track entity/creature totals for metrics. Expose run mode to dev panel and show new counts. * perf(render): frustum cull entities before instance building Add frustum culling to entity instance data collection using AABB vs camera frustum planes. Pass renderer into get_instances_data_map to compute MVP and extract planes. Also add "Rendered Entities" debug counter for visibility. * feat(audio): add ambient pig sounds Add pig call audio with randomized timing, triggered by proximity to the player as 3D positional sound. * feat(client-entity): use snapshot history for entity interpolation Replace exponential smoothing with a buffered snapshot system. Each entity keeps a deque of position/direction snapshots with timestamps; the render transform is interpolated at a fixed 100 ms render delay to hide network jitter. Snapshots are capped to 16 entries. * refactor(hitbox): move player hitbox definition to JSON asset * feat(client_player): use snapshot interpolation for remote players Replace exponential position smoothing with snapshot interpolation. Remote player transforms are rendered from a delayed snapshot history, using linear interpolation for position and shortest-path interpolation for yaw/pitch. A 100 ms render delay compensates for network tick rate.
722 lines
27 KiB
C++
722 lines
27 KiB
C++
// Tencent is pleased to support the open source community by making RapidJSON available.
|
|
//
|
|
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip.
|
|
//
|
|
// Licensed under the MIT License (the "License"); you may not use this file except
|
|
// in compliance with the License. You may obtain a copy of the License at
|
|
//
|
|
// http://opensource.org/licenses/MIT
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software distributed
|
|
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
// specific language governing permissions and limitations under the License.
|
|
|
|
#ifndef RAPIDJSON_WRITER_H_
|
|
#define RAPIDJSON_WRITER_H_
|
|
|
|
#include "stream.h"
|
|
#include "internal/clzll.h"
|
|
#include "internal/meta.h"
|
|
#include "internal/stack.h"
|
|
#include "internal/strfunc.h"
|
|
#include "internal/dtoa.h"
|
|
#include "internal/itoa.h"
|
|
#include "stringbuffer.h"
|
|
#include <new> // placement new
|
|
|
|
#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
|
|
#include <intrin.h>
|
|
#pragma intrinsic(_BitScanForward)
|
|
#endif
|
|
#ifdef RAPIDJSON_SSE42
|
|
#include <nmmintrin.h>
|
|
#elif defined(RAPIDJSON_SSE2)
|
|
#include <emmintrin.h>
|
|
#elif defined(RAPIDJSON_NEON)
|
|
#include <arm_neon.h>
|
|
#endif
|
|
|
|
#ifdef __clang__
|
|
RAPIDJSON_DIAG_PUSH
|
|
RAPIDJSON_DIAG_OFF(padded)
|
|
RAPIDJSON_DIAG_OFF(unreachable-code)
|
|
RAPIDJSON_DIAG_OFF(c++98-compat)
|
|
#elif defined(_MSC_VER)
|
|
RAPIDJSON_DIAG_PUSH
|
|
RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
|
|
#endif
|
|
|
|
RAPIDJSON_NAMESPACE_BEGIN
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
// WriteFlag
|
|
|
|
/*! \def RAPIDJSON_WRITE_DEFAULT_FLAGS
|
|
\ingroup RAPIDJSON_CONFIG
|
|
\brief User-defined kWriteDefaultFlags definition.
|
|
|
|
User can define this as any \c WriteFlag combinations.
|
|
*/
|
|
#ifndef RAPIDJSON_WRITE_DEFAULT_FLAGS
|
|
#define RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags
|
|
#endif
|
|
|
|
//! Combination of writeFlags
|
|
enum WriteFlag {
|
|
kWriteNoFlags = 0, //!< No flags are set.
|
|
kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings.
|
|
kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN.
|
|
kWriteNanAndInfNullFlag = 4, //!< Allow writing of Infinity, -Infinity and NaN as null.
|
|
kWriteDefaultFlags = RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized by defining RAPIDJSON_WRITE_DEFAULT_FLAGS
|
|
};
|
|
|
|
//! JSON writer
|
|
/*! Writer implements the concept Handler.
|
|
It generates JSON text by events to an output os.
|
|
|
|
User may programmatically calls the functions of a writer to generate JSON text.
|
|
|
|
On the other side, a writer can also be passed to objects that generates events,
|
|
|
|
for example Reader::Parse() and Document::Accept().
|
|
|
|
\tparam OutputStream Type of output stream.
|
|
\tparam SourceEncoding Encoding of source string.
|
|
\tparam TargetEncoding Encoding of output stream.
|
|
\tparam StackAllocator Type of allocator for allocating memory of stack.
|
|
\note implements Handler concept
|
|
*/
|
|
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
|
|
class Writer {
|
|
public:
|
|
typedef typename SourceEncoding::Ch Ch;
|
|
|
|
static const int kDefaultMaxDecimalPlaces = 324;
|
|
|
|
//! Constructor
|
|
/*! \param os Output stream.
|
|
\param stackAllocator User supplied allocator. If it is null, it will create a private one.
|
|
\param levelDepth Initial capacity of stack.
|
|
*/
|
|
explicit
|
|
Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) :
|
|
os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}
|
|
|
|
explicit
|
|
Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
|
|
os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}
|
|
|
|
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
|
|
Writer(Writer&& rhs) :
|
|
os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) {
|
|
rhs.os_ = 0;
|
|
}
|
|
#endif
|
|
|
|
//! Reset the writer with a new stream.
|
|
/*!
|
|
This function reset the writer with a new stream and default settings,
|
|
in order to make a Writer object reusable for output multiple JSONs.
|
|
|
|
\param os New output stream.
|
|
\code
|
|
Writer<OutputStream> writer(os1);
|
|
writer.StartObject();
|
|
// ...
|
|
writer.EndObject();
|
|
|
|
writer.Reset(os2);
|
|
writer.StartObject();
|
|
// ...
|
|
writer.EndObject();
|
|
\endcode
|
|
*/
|
|
void Reset(OutputStream& os) {
|
|
os_ = &os;
|
|
hasRoot_ = false;
|
|
level_stack_.Clear();
|
|
}
|
|
|
|
//! Checks whether the output is a complete JSON.
|
|
/*!
|
|
A complete JSON has a complete root object or array.
|
|
*/
|
|
bool IsComplete() const {
|
|
return hasRoot_ && level_stack_.Empty();
|
|
}
|
|
|
|
int GetMaxDecimalPlaces() const {
|
|
return maxDecimalPlaces_;
|
|
}
|
|
|
|
//! Sets the maximum number of decimal places for double output.
|
|
/*!
|
|
This setting truncates the output with specified number of decimal places.
|
|
|
|
For example,
|
|
|
|
\code
|
|
writer.SetMaxDecimalPlaces(3);
|
|
writer.StartArray();
|
|
writer.Double(0.12345); // "0.123"
|
|
writer.Double(0.0001); // "0.0"
|
|
writer.Double(1.234567890123456e30); // "1.234567890123456e30" (do not truncate significand for positive exponent)
|
|
writer.Double(1.23e-4); // "0.0" (do truncate significand for negative exponent)
|
|
writer.EndArray();
|
|
\endcode
|
|
|
|
The default setting does not truncate any decimal places. You can restore to this setting by calling
|
|
\code
|
|
writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces);
|
|
\endcode
|
|
*/
|
|
void SetMaxDecimalPlaces(int maxDecimalPlaces) {
|
|
maxDecimalPlaces_ = maxDecimalPlaces;
|
|
}
|
|
|
|
/*!@name Implementation of Handler
|
|
\see Handler
|
|
*/
|
|
//@{
|
|
|
|
bool Null() { Prefix(kNullType); return EndValue(WriteNull()); }
|
|
bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return EndValue(WriteBool(b)); }
|
|
bool Int(int i) { Prefix(kNumberType); return EndValue(WriteInt(i)); }
|
|
bool Uint(unsigned u) { Prefix(kNumberType); return EndValue(WriteUint(u)); }
|
|
bool Int64(int64_t i64) { Prefix(kNumberType); return EndValue(WriteInt64(i64)); }
|
|
bool Uint64(uint64_t u64) { Prefix(kNumberType); return EndValue(WriteUint64(u64)); }
|
|
|
|
//! Writes the given \c double value to the stream
|
|
/*!
|
|
\param d The value to be written.
|
|
\return Whether it is succeed.
|
|
*/
|
|
bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); }
|
|
|
|
bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
|
|
RAPIDJSON_ASSERT(str != 0);
|
|
(void)copy;
|
|
Prefix(kNumberType);
|
|
return EndValue(WriteString(str, length));
|
|
}
|
|
|
|
bool String(const Ch* str, SizeType length, bool copy = false) {
|
|
RAPIDJSON_ASSERT(str != 0);
|
|
(void)copy;
|
|
Prefix(kStringType);
|
|
return EndValue(WriteString(str, length));
|
|
}
|
|
|
|
#if RAPIDJSON_HAS_STDSTRING
|
|
bool String(const std::basic_string<Ch>& str) {
|
|
return String(str.data(), SizeType(str.size()));
|
|
}
|
|
#endif
|
|
|
|
bool StartObject() {
|
|
Prefix(kObjectType);
|
|
new (level_stack_.template Push<Level>()) Level(false);
|
|
return WriteStartObject();
|
|
}
|
|
|
|
bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
|
|
|
|
#if RAPIDJSON_HAS_STDSTRING
|
|
bool Key(const std::basic_string<Ch>& str)
|
|
{
|
|
return Key(str.data(), SizeType(str.size()));
|
|
}
|
|
#endif
|
|
|
|
bool EndObject(SizeType memberCount = 0) {
|
|
(void)memberCount;
|
|
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); // not inside an Object
|
|
RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray); // currently inside an Array, not Object
|
|
RAPIDJSON_ASSERT(0 == level_stack_.template Top<Level>()->valueCount % 2); // Object has a Key without a Value
|
|
level_stack_.template Pop<Level>(1);
|
|
return EndValue(WriteEndObject());
|
|
}
|
|
|
|
bool StartArray() {
|
|
Prefix(kArrayType);
|
|
new (level_stack_.template Push<Level>()) Level(true);
|
|
return WriteStartArray();
|
|
}
|
|
|
|
bool EndArray(SizeType elementCount = 0) {
|
|
(void)elementCount;
|
|
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
|
|
RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
|
|
level_stack_.template Pop<Level>(1);
|
|
return EndValue(WriteEndArray());
|
|
}
|
|
//@}
|
|
|
|
/*! @name Convenience extensions */
|
|
//@{
|
|
|
|
//! Simpler but slower overload.
|
|
bool String(const Ch* const& str) { return String(str, internal::StrLen(str)); }
|
|
bool Key(const Ch* const& str) { return Key(str, internal::StrLen(str)); }
|
|
|
|
//@}
|
|
|
|
//! Write a raw JSON value.
|
|
/*!
|
|
For user to write a stringified JSON as a value.
|
|
|
|
\param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
|
|
\param length Length of the json.
|
|
\param type Type of the root of json.
|
|
*/
|
|
bool RawValue(const Ch* json, size_t length, Type type) {
|
|
RAPIDJSON_ASSERT(json != 0);
|
|
Prefix(type);
|
|
return EndValue(WriteRawValue(json, length));
|
|
}
|
|
|
|
//! Flush the output stream.
|
|
/*!
|
|
Allows the user to flush the output stream immediately.
|
|
*/
|
|
void Flush() {
|
|
os_->Flush();
|
|
}
|
|
|
|
static const size_t kDefaultLevelDepth = 32;
|
|
|
|
protected:
|
|
//! Information for each nested level
|
|
struct Level {
|
|
Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
|
|
size_t valueCount; //!< number of values in this level
|
|
bool inArray; //!< true if in array, otherwise in object
|
|
};
|
|
|
|
bool WriteNull() {
|
|
PutReserve(*os_, 4);
|
|
PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true;
|
|
}
|
|
|
|
bool WriteBool(bool b) {
|
|
if (b) {
|
|
PutReserve(*os_, 4);
|
|
PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e');
|
|
}
|
|
else {
|
|
PutReserve(*os_, 5);
|
|
PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e');
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool WriteInt(int i) {
|
|
char buffer[11];
|
|
const char* end = internal::i32toa(i, buffer);
|
|
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
|
for (const char* p = buffer; p != end; ++p)
|
|
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
|
return true;
|
|
}
|
|
|
|
bool WriteUint(unsigned u) {
|
|
char buffer[10];
|
|
const char* end = internal::u32toa(u, buffer);
|
|
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
|
for (const char* p = buffer; p != end; ++p)
|
|
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
|
return true;
|
|
}
|
|
|
|
bool WriteInt64(int64_t i64) {
|
|
char buffer[21];
|
|
const char* end = internal::i64toa(i64, buffer);
|
|
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
|
for (const char* p = buffer; p != end; ++p)
|
|
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
|
return true;
|
|
}
|
|
|
|
bool WriteUint64(uint64_t u64) {
|
|
char buffer[20];
|
|
char* end = internal::u64toa(u64, buffer);
|
|
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
|
for (char* p = buffer; p != end; ++p)
|
|
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
|
return true;
|
|
}
|
|
|
|
bool WriteDouble(double d) {
|
|
if (internal::Double(d).IsNanOrInf()) {
|
|
if (!(writeFlags & kWriteNanAndInfFlag) && !(writeFlags & kWriteNanAndInfNullFlag))
|
|
return false;
|
|
if (writeFlags & kWriteNanAndInfNullFlag) {
|
|
PutReserve(*os_, 4);
|
|
PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l');
|
|
return true;
|
|
}
|
|
if (internal::Double(d).IsNan()) {
|
|
PutReserve(*os_, 3);
|
|
PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
|
|
return true;
|
|
}
|
|
if (internal::Double(d).Sign()) {
|
|
PutReserve(*os_, 9);
|
|
PutUnsafe(*os_, '-');
|
|
}
|
|
else
|
|
PutReserve(*os_, 8);
|
|
PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
|
|
PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
|
|
return true;
|
|
}
|
|
|
|
char buffer[25];
|
|
char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
|
|
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
|
for (char* p = buffer; p != end; ++p)
|
|
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
|
return true;
|
|
}
|
|
|
|
bool WriteString(const Ch* str, SizeType length) {
|
|
static const typename OutputStream::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
|
|
static const char escape[256] = {
|
|
#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
|
//0 1 2 3 4 5 6 7 8 9 A B C D E F
|
|
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
|
|
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
|
|
0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
|
|
Z16, Z16, // 30~4F
|
|
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50
|
|
Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF
|
|
#undef Z16
|
|
};
|
|
|
|
if (TargetEncoding::supportUnicode)
|
|
PutReserve(*os_, 2 + length * 6); // "\uxxxx..."
|
|
else
|
|
PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..."
|
|
|
|
PutUnsafe(*os_, '\"');
|
|
GenericStringStream<SourceEncoding> is(str);
|
|
while (ScanWriteUnescapedString(is, length)) {
|
|
const Ch c = is.Peek();
|
|
if (!TargetEncoding::supportUnicode && static_cast<unsigned>(c) >= 0x80) {
|
|
// Unicode escaping
|
|
unsigned codepoint;
|
|
if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint)))
|
|
return false;
|
|
PutUnsafe(*os_, '\\');
|
|
PutUnsafe(*os_, 'u');
|
|
if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
|
|
PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(codepoint ) & 15]);
|
|
}
|
|
else {
|
|
RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
|
|
// Surrogate pair
|
|
unsigned s = codepoint - 0x010000;
|
|
unsigned lead = (s >> 10) + 0xD800;
|
|
unsigned trail = (s & 0x3FF) + 0xDC00;
|
|
PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(lead ) & 15]);
|
|
PutUnsafe(*os_, '\\');
|
|
PutUnsafe(*os_, 'u');
|
|
PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]);
|
|
PutUnsafe(*os_, hexDigits[(trail ) & 15]);
|
|
}
|
|
}
|
|
else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) {
|
|
is.Take();
|
|
PutUnsafe(*os_, '\\');
|
|
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(escape[static_cast<unsigned char>(c)]));
|
|
if (escape[static_cast<unsigned char>(c)] == 'u') {
|
|
PutUnsafe(*os_, '0');
|
|
PutUnsafe(*os_, '0');
|
|
PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) >> 4]);
|
|
PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) & 0xF]);
|
|
}
|
|
}
|
|
else if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ?
|
|
Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) :
|
|
Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_))))
|
|
return false;
|
|
}
|
|
PutUnsafe(*os_, '\"');
|
|
return true;
|
|
}
|
|
|
|
bool ScanWriteUnescapedString(GenericStringStream<SourceEncoding>& is, size_t length) {
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
}
|
|
|
|
bool WriteStartObject() { os_->Put('{'); return true; }
|
|
bool WriteEndObject() { os_->Put('}'); return true; }
|
|
bool WriteStartArray() { os_->Put('['); return true; }
|
|
bool WriteEndArray() { os_->Put(']'); return true; }
|
|
|
|
bool WriteRawValue(const Ch* json, size_t length) {
|
|
PutReserve(*os_, length);
|
|
GenericStringStream<SourceEncoding> is(json);
|
|
while (RAPIDJSON_LIKELY(is.Tell() < length)) {
|
|
RAPIDJSON_ASSERT(is.Peek() != '\0');
|
|
if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ?
|
|
Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) :
|
|
Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_))))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void Prefix(Type type) {
|
|
(void)type;
|
|
if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root
|
|
Level* level = level_stack_.template Top<Level>();
|
|
if (level->valueCount > 0) {
|
|
if (level->inArray)
|
|
os_->Put(','); // add comma if it is not the first element in array
|
|
else // in object
|
|
os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
|
|
}
|
|
if (!level->inArray && level->valueCount % 2 == 0)
|
|
RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
|
|
level->valueCount++;
|
|
}
|
|
else {
|
|
RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root.
|
|
hasRoot_ = true;
|
|
}
|
|
}
|
|
|
|
// Flush the value if it is the top level one.
|
|
bool EndValue(bool ret) {
|
|
if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
|
|
Flush();
|
|
return ret;
|
|
}
|
|
|
|
OutputStream* os_;
|
|
internal::Stack<StackAllocator> level_stack_;
|
|
int maxDecimalPlaces_;
|
|
bool hasRoot_;
|
|
|
|
private:
|
|
// Prohibit copy constructor & assignment operator.
|
|
Writer(const Writer&);
|
|
Writer& operator=(const Writer&);
|
|
};
|
|
|
|
// Full specialization for StringStream to prevent memory copying
|
|
|
|
template<>
|
|
inline bool Writer<StringBuffer>::WriteInt(int i) {
|
|
char *buffer = os_->Push(11);
|
|
const char* end = internal::i32toa(i, buffer);
|
|
os_->Pop(static_cast<size_t>(11 - (end - buffer)));
|
|
return true;
|
|
}
|
|
|
|
template<>
|
|
inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
|
|
char *buffer = os_->Push(10);
|
|
const char* end = internal::u32toa(u, buffer);
|
|
os_->Pop(static_cast<size_t>(10 - (end - buffer)));
|
|
return true;
|
|
}
|
|
|
|
template<>
|
|
inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
|
|
char *buffer = os_->Push(21);
|
|
const char* end = internal::i64toa(i64, buffer);
|
|
os_->Pop(static_cast<size_t>(21 - (end - buffer)));
|
|
return true;
|
|
}
|
|
|
|
template<>
|
|
inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
|
|
char *buffer = os_->Push(20);
|
|
const char* end = internal::u64toa(u, buffer);
|
|
os_->Pop(static_cast<size_t>(20 - (end - buffer)));
|
|
return true;
|
|
}
|
|
|
|
template<>
|
|
inline bool Writer<StringBuffer>::WriteDouble(double d) {
|
|
if (internal::Double(d).IsNanOrInf()) {
|
|
// Note: This code path can only be reached if (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag).
|
|
if (!(kWriteDefaultFlags & kWriteNanAndInfFlag))
|
|
return false;
|
|
if (kWriteDefaultFlags & kWriteNanAndInfNullFlag) {
|
|
PutReserve(*os_, 4);
|
|
PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l');
|
|
return true;
|
|
}
|
|
if (internal::Double(d).IsNan()) {
|
|
PutReserve(*os_, 3);
|
|
PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
|
|
return true;
|
|
}
|
|
if (internal::Double(d).Sign()) {
|
|
PutReserve(*os_, 9);
|
|
PutUnsafe(*os_, '-');
|
|
}
|
|
else
|
|
PutReserve(*os_, 8);
|
|
PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
|
|
PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
|
|
return true;
|
|
}
|
|
|
|
char *buffer = os_->Push(25);
|
|
char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
|
|
os_->Pop(static_cast<size_t>(25 - (end - buffer)));
|
|
return true;
|
|
}
|
|
|
|
#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
|
|
template<>
|
|
inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
|
|
if (length < 16)
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
|
|
if (!RAPIDJSON_LIKELY(is.Tell() < length))
|
|
return false;
|
|
|
|
const char* p = is.src_;
|
|
const char* end = is.head_ + length;
|
|
const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
|
|
const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
|
|
if (nextAligned > end)
|
|
return true;
|
|
|
|
while (p != nextAligned)
|
|
if (*p < 0x20 || *p == '\"' || *p == '\\') {
|
|
is.src_ = p;
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
}
|
|
else
|
|
os_->PutUnsafe(*p++);
|
|
|
|
// The rest of string using SIMD
|
|
static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
|
|
static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
|
|
static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
|
|
const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
|
|
const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
|
|
const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
|
|
|
|
for (; p != endAligned; p += 16) {
|
|
const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
|
|
const __m128i t1 = _mm_cmpeq_epi8(s, dq);
|
|
const __m128i t2 = _mm_cmpeq_epi8(s, bs);
|
|
const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
|
|
const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
|
|
unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
|
|
if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
|
|
SizeType len;
|
|
#ifdef _MSC_VER // Find the index of first escaped
|
|
unsigned long offset;
|
|
_BitScanForward(&offset, r);
|
|
len = offset;
|
|
#else
|
|
len = static_cast<SizeType>(__builtin_ffs(r) - 1);
|
|
#endif
|
|
char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
|
|
for (size_t i = 0; i < len; i++)
|
|
q[i] = p[i];
|
|
|
|
p += len;
|
|
break;
|
|
}
|
|
_mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s);
|
|
}
|
|
|
|
is.src_ = p;
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
}
|
|
#elif defined(RAPIDJSON_NEON)
|
|
template<>
|
|
inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
|
|
if (length < 16)
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
|
|
if (!RAPIDJSON_LIKELY(is.Tell() < length))
|
|
return false;
|
|
|
|
const char* p = is.src_;
|
|
const char* end = is.head_ + length;
|
|
const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
|
|
const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
|
|
if (nextAligned > end)
|
|
return true;
|
|
|
|
while (p != nextAligned)
|
|
if (*p < 0x20 || *p == '\"' || *p == '\\') {
|
|
is.src_ = p;
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
}
|
|
else
|
|
os_->PutUnsafe(*p++);
|
|
|
|
// The rest of string using SIMD
|
|
const uint8x16_t s0 = vmovq_n_u8('"');
|
|
const uint8x16_t s1 = vmovq_n_u8('\\');
|
|
const uint8x16_t s2 = vmovq_n_u8('\b');
|
|
const uint8x16_t s3 = vmovq_n_u8(32);
|
|
|
|
for (; p != endAligned; p += 16) {
|
|
const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
|
|
uint8x16_t x = vceqq_u8(s, s0);
|
|
x = vorrq_u8(x, vceqq_u8(s, s1));
|
|
x = vorrq_u8(x, vceqq_u8(s, s2));
|
|
x = vorrq_u8(x, vcltq_u8(s, s3));
|
|
|
|
x = vrev64q_u8(x); // Rev in 64
|
|
uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract
|
|
uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract
|
|
|
|
SizeType len = 0;
|
|
bool escaped = false;
|
|
if (low == 0) {
|
|
if (high != 0) {
|
|
uint32_t lz = internal::clzll(high);
|
|
len = 8 + (lz >> 3);
|
|
escaped = true;
|
|
}
|
|
} else {
|
|
uint32_t lz = internal::clzll(low);
|
|
len = lz >> 3;
|
|
escaped = true;
|
|
}
|
|
if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped
|
|
char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
|
|
for (size_t i = 0; i < len; i++)
|
|
q[i] = p[i];
|
|
|
|
p += len;
|
|
break;
|
|
}
|
|
vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s);
|
|
}
|
|
|
|
is.src_ = p;
|
|
return RAPIDJSON_LIKELY(is.Tell() < length);
|
|
}
|
|
#endif // RAPIDJSON_NEON
|
|
|
|
RAPIDJSON_NAMESPACE_END
|
|
|
|
#if defined(_MSC_VER) || defined(__clang__)
|
|
RAPIDJSON_DIAG_POP
|
|
#endif
|
|
|
|
#endif // RAPIDJSON_RAPIDJSON_H_
|