Skip to content

WIP For Infinite Terrain Generation, Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block.#1047

Open
starseed12345 wants to merge 32 commits intosmartcmd:mainfrom
starseed12345:main
Open

WIP For Infinite Terrain Generation, Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block.#1047
starseed12345 wants to merge 32 commits intosmartcmd:mainfrom
starseed12345:main

Conversation

@starseed12345
Copy link

Description

This PR introduces several CPU overhead optimizations in pathfinding, entity logic, and entity shadow rendering.
The changes reduce repeated smart pointer operations and avoid redundant world lookups during shadow rendering.

Changes
Previous Behavior

serverAiStep repeatedly called shared_from_this() inside the function.

Entity logic performed unnecessary shared_ptr operations in hot paths.

Shadow rendering repeatedly queried Level::getTile and Level::getRawBrightness for the same blocks during a single frame.

These operations added unnecessary CPU overhead during entity updates and rendering.

Root Cause

Repeated shared_from_this() calls caused avoidable reference counting overhead.

Some entity rendering paths unnecessarily copied shared_ptr values.

Shadow rendering performed redundant world queries inside nested loops.

New Behavior

shared_from_this() is cached once in serverAiStep and reused.

Several entity functions reduce unnecessary shared_ptr overhead.

Shadow rendering caches tile ID and brightness values per block during a frame.

This reduces repeated computations and improves CPU efficiency in both entity logic and rendering.

Fix Implementation

Cached shared_from_this() at the beginning of serverAiStep and reused the result.

Reduced unnecessary shared_ptr copies in entity-related code paths.

Added shadowTileCache in EntityRenderDispatcher to cache:

tile ID

brightness

Introduced beginFrame() to clear the cache once per frame.

Updated renderShadow to reuse cached tile data instead of performing repeated world lookups.

AI Use Disclosure

AI was used to make the description of this pull request

Related Issues
None

- Cache shared_from_this() in serverAiStep
- Reduce shared_ptr overhead in entities
- Add shadow tile cache to optimize entity shadow rendering
@starseed12345
Copy link
Author

I'd also like it if someone could compare the performance results/cpu usage and let me know if i did any mistakes in the code

Tuff-CWC and others added 12 commits March 9, 2026 15:02
This set of changes was made to make the code better mimic TU20 based on its disassembly
It was never even enabled properly to begin with
writeRuleFile() was missing the schematic file count integer before the schematic entries. The reader in readRuleFile() expected this count, causing a stream misalignment that led to an assertion failure (Unrecognised schematic version) when reloading a saved tutorial world.

The fix writes the count on save and adds backward-compatible reading that detects old saves (without count) via a peek heuristic and falls back to count-less parsing.

Co-authored-by: MCbabel <MCbabel@users.noreply.github.com>
Fixed endermans by making a invulnerable check
Co-authored-by: MCbabel <MCbabel@users.noreply.github.com>
…rtcmd#992)

* Fixed bug where Bonus Chests would spawn again when loading back into it.

Fixes smartcmd#982

Added a check for if the world is new.

Meaning no more additional chests if the world is loaded up again.

* Replace NULL with nullptr for chest check
smartcmd#1089)

* Fix for issue where player is able to stay alive with zero hearts in their healthbar.

* use static cast over c style cast
Placing Buttons On the ceiling or the floor of a block was introduced later i reintroduced this feature which matches it 1:1 to vanilla
@starseed12345 starseed12345 changed the title Reduce CPU overhead in pathfinding, entity logic, and shadow rendering Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block Mar 10, 2026
codeHusky and others added 15 commits March 10, 2026 09:37
* fixed all DLC maps

* fixed old saves have overlapping chunks with the new system
Signed-off-by: Ayush Thoren <ayushthoren@gmail.com>
Co-authored-by: RatCatcherVr <littlerat111811@gmail.com>
* Fix split-screen join failing when connecting to a remote host via UI

When a non-host client connected to a remote server through the in-game
UI (as opposed to the -ip/-port command line flags), the global variables
g_Win64MultiplayerIP and g_Win64MultiplayerPort were never updated from
their defaults ("127.0.0.1" and the default port). JoinSplitScreen()
relies on these globals to open a second TCP connection for the local
split-screen pad, so it would always attempt to connect to localhost,
failing immediately on any remote session.

Fix: update g_Win64MultiplayerIP and g_Win64MultiplayerPort inside
JoinGame() once the primary connection is established. This ensures
subsequent JoinSplitScreen() calls always reach the correct host
regardless of how the session was joined.

Additionally, guard PushFreeSmallId() against recycling smallIds in the
range [0, XUSER_MAX_COUNT), which are permanently reserved for the
host's local controller slots. Previously, if a host-side local pad
disconnected its smallId could re-enter the free pool and be handed
to an incoming remote client, causing that client's IQNetPlayer slot
to collide with a local pad slot on the non-host machine.

* Fix tutorial popup positioning in split-screen viewports

Replace the manual switch-case that computed viewport origin with the shared GetViewportRect/Fit16x9 helpers (from UISplitScreenHelpers.h). This ensures the tutorial popup is positioned and scaled consistently with the rest of the split-screen UI, fitting a 16:9 box inside each viewport and applying safezone offsets correctly.

Also adds missing default:break to safezone switch statements to silence compiler warnings.

Made-with: Cursor

* Prevent split-screen join when game window is not focused

Add g_KBMInput.IsWindowFocused() guard to the tryJoin condition so that gamepad input from background windows does not accidentally trigger a split-screen player join. This avoids phantom joins when the user is interacting with another application.

* Open debug overlay in fullscreen UI group during split-screen

Pass eUIGroup_Fullscreen to NavigateToScene when opening the debug overlay, so it spans the entire window instead of being confined to a single split-screen viewport. This makes the debug info readable regardless of the current split-screen layout.

* Fix non-host split-screen connections missing world updates

Previously, secondary (non-host) split-screen connections used isPrimaryConnection()
to gate nearly all world update packets, meaning the second local player would never
receive tile updates, entity movement, sounds, particles, explosions, etc.

The fix introduces per-connection tracking of which entities and chunks each
ClientConnection has loaded, and uses that information to decide whether a secondary
connection needs to process a given packet or if the primary connection already
handled it.

New members in ClientConnection:
- m_trackedEntityIds: set of entity IDs this connection has received AddEntity/AddMob/AddPlayer etc. for
- m_visibleChunks: set of chunk coordinates (packed into int64) this connection has marked visible
- Both sets are cleared on close(), respawn (dimension change), and destructor

New helpers:
- findPrimaryConnection(): walks the MultiPlayerLevel connection list to find the connection on the primary pad
- shouldProcessForEntity(id): secondary connection skips the packet only if the primary is already tracking that entity
- shouldProcessForPosition(x, z): secondary connection skips the packet only if the primary already has that chunk visible
- anyOtherConnectionHasChunk(x, z): used when a chunk becomes invisible to avoid hiding it from the level if another connection still needs it
- isTrackingEntity(id): public accessor used by shouldProcessForEntity on the primary connection

Packet handler changes:
- handleMoveEntity, handleMoveEntitySmall, handleSetEntityMotion, handleTakeItemEntity:
  replaced isPrimaryConnection() with shouldProcessForEntity() so secondary
  connections still process movement for entities they know about
- handleExplosion, handleLevelEvent:
  replaced isPrimaryConnection() with shouldProcessForPosition() so block
  destruction and level events fire for the correct connection based on chunks
- handleChunkTilesUpdate, handleBlockRegionUpdate, handleTileUpdate, handleSignUpdate,
  handleTileEntityData, handleTileEvent, handleTileDestruction, handleComplexItemData,
  handleSoundEvent, handleParticleEvent:
  removed the isPrimaryConnection() guard entirely -- these are world-state updates
  that all connections must process regardless of which pad is primary
- handleChunkVisibilityArea / handleChunkVisibility:
  now populate m_visibleChunks; on visibility=false, setChunkVisible(false) is
  only called on the level if no other connection still has that chunk loaded
- handleAddEntity, handleAddExperienceOrb, handleAddPainting, handleAddPlayer,
  handleAddMob: now insert into m_trackedEntityIds on arrival
- handleRemoveEntity: now erases from m_trackedEntityIds on removal
- handleLevelEvent: removed a duplicate levelEvent() call that was always firing
  regardless of the isPrimaryConnection() check above it (latent bug)

MultiPlayerLevel: added friend class ClientConnection to allow access to the
connections list without exposing it publicly.

* Fix fullscreen progress screen swallowing input before load completes

Two issues in UIScene_FullscreenProgress::handleInput:

1. The touchpad/button press that triggers movie skip or input forwarding
   had no guard on m_threadCompleted, so pressing a button during the loading
   phase would fire the skip/send logic before the background thread finished.
   Added the m_threadCompleted check so that path is only reachable once
   the load is actually done.

2. The `handled = true` assignment was missing from that branch, so input
   events were not being consumed and could fall through to other handlers.
   Added it unconditionally at the end of the block.

* Update player count decrement logic in PlatformNetworkManagerStub

Refactor the condition for decrementing the player count in CPlatformNetworkManagerStub::DoWork. The previous check was replaced with a while loop to ensure that the player count is only decremented when there are more than one player and the last player's custom data value is zero. This change improves the handling of player connections in the network manager.

* Refactor safe zone calculations in UI components for consistency

Updated the safe zone calculations across multiple UI components to ensure symmetry in split viewports. Removed unnecessary assignments and added comments for clarity. Modified the repositionHud function to include an additional parameter for better handling of HUD positioning in split-screen scenarios.

* Gui.cpp: fix F3 debug overlay in splitscreen + minor perf cleanup

The F3 debug screen was badly broken in splitscreen: it used the GUI
coordinate space which gets distorted by the splitscreen scaling, so
text appeared stretched, misaligned or completely off-screen depending
on the viewport layout.

Fixed by setting up a dedicated projection matrix using physical pixel
coordinates (g_rScreenWidth / g_rScreenHeight) each time the overlay is
drawn, completely decoupled from whatever transform the HUD is using.
The viewport dimensions are now computed per screen section so the ortho
projection matches the actual pixel area of each player's quadrant.
Version and branch strings are only shown for player 0 (iPad == 0) to
avoid repeating them across every splitscreen pane.

Also removed a few redundant calculations that were being done twice in
the same frame (atan for xRot, health halves, air supply scaled value).
These are minor and have negligible real-world impact; more substantial
per-frame caching work (safe zone calculations etc.) will follow in a
separate commit.
* Fix mounted minecarts not persisting across world reloads

Signed-off-by: Ayush Thoren <ayushthoren@gmail.com>

* Apply patch

---------

Signed-off-by: Ayush Thoren <ayushthoren@gmail.com>
* fix: witches' bottle is now the right color

* fix: add condition if item has mutiple layers
* Remove all old binka redist files

* Delete x64/Debug/Effects.msscmp

* Delete x64/Release/Effects.msscmp
current issue is "Infinite" text wont show up and we can't change level_max_width to 30 million as getGlobalChunkCount() = overworldSize * overworldSize * CHUNK_Y_COUNT so we will be getting a bad_alloc error on boot
Strangely "Infinite" World size text remains invisible if anyone can check that out
@starseed12345 starseed12345 changed the title Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block WIP For Infinite Terrain Generationm, Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block. Mar 13, 2026
@starseed12345 starseed12345 changed the title WIP For Infinite Terrain Generationm, Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block. WIP For Infinite Terrain Generation, Reduce CPU overhead in pathfinding, entity logic, and shadow rendering. Button Placement for ceiling and floor of Block. Mar 14, 2026
I will keep the infinite world gen base like this so someone else can finish it off. I don't have the necessary skills to recode the entire codebase just for infinite terrain generation + correct structure placement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.