@nice2dev/game-engine 1.3.15 → 1.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (434) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/cjs/accessibility/Accessibility.js +152 -165
  3. package/dist/cjs/ai/AI.js +292 -294
  4. package/dist/cjs/ai/BehaviorTree.js +1029 -1113
  5. package/dist/cjs/ai/StateMachine.js +694 -756
  6. package/dist/cjs/animation/Animation.js +232 -241
  7. package/dist/cjs/audio/AudioAdvanced.js +221 -236
  8. package/dist/cjs/audio/AudioBridge.js +441 -435
  9. package/dist/cjs/audio/AudioManager.js +242 -259
  10. package/dist/cjs/build-cloud/BuildOrchestration.js +1059 -1098
  11. package/dist/cjs/build-cloud/GodotBuildCloud.js +641 -670
  12. package/dist/cjs/build-cloud/UnityBuildCloud.js +563 -610
  13. package/dist/cjs/build-cloud/UnrealBuildCloud.js +610 -635
  14. package/dist/cjs/core/EventBus.js +51 -56
  15. package/dist/cjs/core/GameClock.js +62 -66
  16. package/dist/cjs/core/GameConfig.js +72 -79
  17. package/dist/cjs/core/GameLoop.js +80 -89
  18. package/dist/cjs/core/ServiceLocator.js +61 -65
  19. package/dist/cjs/core/Validation.js +72 -82
  20. package/dist/cjs/core/math.js +108 -112
  21. package/dist/cjs/devtools/DevTools.js +542 -563
  22. package/dist/cjs/devtools/DeveloperExperience.js +521 -559
  23. package/dist/cjs/devtools/GameplayAnalytics.js +636 -646
  24. package/dist/cjs/dialogue/DialogueSystem.js +984 -986
  25. package/dist/cjs/docs/DocGenerator.js +339 -364
  26. package/dist/cjs/ecs/World.js +355 -371
  27. package/dist/cjs/editor/AchievementEditor.js +580 -636
  28. package/dist/cjs/editor/AdvancedEditor.js +184 -191
  29. package/dist/cjs/editor/AnimationRetargeting.js +696 -741
  30. package/dist/cjs/editor/AssetBrowser.js +1072 -1160
  31. package/dist/cjs/editor/AssetManager.js +187 -192
  32. package/dist/cjs/editor/ConsolePro.js +971 -1061
  33. package/dist/cjs/editor/CraftingEditor.js +680 -730
  34. package/dist/cjs/editor/DebugTools.js +187 -185
  35. package/dist/cjs/editor/DialogueSystem.js +844 -901
  36. package/dist/cjs/editor/LeaderboardSystem.js +429 -483
  37. package/dist/cjs/editor/NiceGameEditor.js +1903 -1201
  38. package/dist/cjs/editor/PrefabSystem.js +772 -838
  39. package/dist/cjs/editor/ProfilerPanel.js +649 -700
  40. package/dist/cjs/editor/QuestEditor.js +792 -839
  41. package/dist/cjs/editor/ReplaySystem.js +585 -634
  42. package/dist/cjs/editor/SceneEditor.js +176 -200
  43. package/dist/cjs/editor/ScreenshotMode.js +621 -688
  44. package/dist/cjs/editor/ShaderGraph.js +1556 -1582
  45. package/dist/cjs/editor/TimelineEditor.js +715 -778
  46. package/dist/cjs/editor/UndoRedoPro.js +830 -904
  47. package/dist/cjs/editor/VRARMode.js +582 -645
  48. package/dist/cjs/engine/NiceGameEngine.js +141 -164
  49. package/dist/cjs/engine/SaveSystem.js +441 -495
  50. package/dist/cjs/enterprise/Enterprise.js +254 -261
  51. package/dist/cjs/export/BevyExporter.js +927 -967
  52. package/dist/cjs/export/CocosExporter.js +644 -673
  53. package/dist/cjs/export/Construct3Exporter.js +783 -794
  54. package/dist/cjs/export/DefoldExporter.js +1028 -1069
  55. package/dist/cjs/export/GDevelopExporter.js +674 -708
  56. package/dist/cjs/export/GameMakerExporter.js +791 -805
  57. package/dist/cjs/export/GodotExporter.js +1003 -1045
  58. package/dist/cjs/export/MinecraftBedrockExporter.js +573 -578
  59. package/dist/cjs/export/MonoGameExporter.js +1265 -1293
  60. package/dist/cjs/export/Pico8Exporter.js +766 -812
  61. package/dist/cjs/export/PlatformExporter.js +188 -206
  62. package/dist/cjs/export/RPGMakerExporter.js +860 -879
  63. package/dist/cjs/export/RobloxExporter.js +883 -919
  64. package/dist/cjs/export/Solar2DExporter.js +1218 -1256
  65. package/dist/cjs/export/ThreeJSExporter.js +1006 -1073
  66. package/dist/cjs/export/Tic80Exporter.js +1210 -1267
  67. package/dist/cjs/export/UnityExporter.js +1116 -1131
  68. package/dist/cjs/export/UnrealExporter.js +889 -919
  69. package/dist/cjs/export/WebExporter.js +931 -970
  70. package/dist/cjs/export/index.js +42 -65
  71. package/dist/cjs/godot-integration/GodotAssetLibrary.js +659 -692
  72. package/dist/cjs/godot-integration/GodotImport.js +929 -1027
  73. package/dist/cjs/godot-integration/GodotLiveLink.js +915 -945
  74. package/dist/cjs/godot-integration/components/GodotProjectBrowser.js +911 -611
  75. package/dist/cjs/i18n/I18n.js +860 -900
  76. package/dist/cjs/i18n/useTranslation.js +84 -89
  77. package/dist/cjs/import/AsepriteImporter.js +658 -716
  78. package/dist/cjs/import/DragonBonesImporter.js +437 -461
  79. package/dist/cjs/import/GameMakerImporter.js +511 -521
  80. package/dist/cjs/import/GodotSceneImporter.js +788 -822
  81. package/dist/cjs/import/LDtkImporter.js +436 -454
  82. package/dist/cjs/import/Live2DImporter.js +497 -518
  83. package/dist/cjs/import/NdgFormat.js +424 -457
  84. package/dist/cjs/import/OgmoImporter.js +466 -493
  85. package/dist/cjs/import/RPGMakerImporter.js +451 -477
  86. package/dist/cjs/import/SceneImporter.js +378 -423
  87. package/dist/cjs/import/SpineImporter.js +511 -546
  88. package/dist/cjs/import/SpriterImporter.js +590 -613
  89. package/dist/cjs/import/TiledMapImporter.js +811 -846
  90. package/dist/cjs/import/UnitySceneImporter.js +687 -703
  91. package/dist/cjs/import/index.js +206 -251
  92. package/dist/cjs/index.js +275 -278
  93. package/dist/cjs/input/GamepadNavigation.js +185 -205
  94. package/dist/cjs/input/InputManager.js +397 -421
  95. package/dist/cjs/input/useGamepads.js +70 -81
  96. package/dist/cjs/integration/IconSprite.js +129 -256
  97. package/dist/cjs/inventory/InventorySystem.js +920 -995
  98. package/dist/cjs/kids/KidMode.js +997 -1022
  99. package/dist/cjs/kids/KidTools.js +570 -594
  100. package/dist/cjs/monetization/Monetization.js +170 -177
  101. package/dist/cjs/multiplayer/LocalMultiplayer.js +287 -287
  102. package/dist/cjs/multiplayer/MiniGameTypes.js +49 -59
  103. package/dist/cjs/native-engine/AnimationSystem.js +731 -806
  104. package/dist/cjs/native-engine/AssetPipeline.js +454 -515
  105. package/dist/cjs/native-engine/AudioEngine.js +763 -804
  106. package/dist/cjs/native-engine/InputSystem.js +1075 -1145
  107. package/dist/cjs/native-engine/NetworkingSystem.js +733 -793
  108. package/dist/cjs/native-engine/PhysicsEngine.js +583 -607
  109. package/dist/cjs/native-engine/RenderingEngine.js +302 -350
  110. package/dist/cjs/native-engine/SceneGraph.js +769 -808
  111. package/dist/cjs/network/MultiplayerTransport.js +97 -132
  112. package/dist/cjs/network/Networking.js +549 -564
  113. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/AbortController.js +21 -29
  114. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/AccessTokenHttpClient.js +40 -48
  115. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/DefaultHttpClient.js +35 -43
  116. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/DefaultReconnectPolicy.js +10 -15
  117. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Errors.js +103 -135
  118. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/FetchHttpClient.js +131 -158
  119. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HandshakeProtocol.js +39 -53
  120. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HeaderNames.js +5 -8
  121. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HttpClient.js +40 -48
  122. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HttpConnection.js +494 -572
  123. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HubConnection.js +826 -953
  124. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HubConnectionBuilder.js +125 -146
  125. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/IHubProtocol.js +13 -23
  126. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/ILogger.js +11 -25
  127. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/ITransport.js +13 -24
  128. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/JsonHubProtocol.js +108 -121
  129. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Loggers.js +10 -14
  130. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/LongPollingTransport.js +150 -185
  131. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/MessageBuffer.js +158 -196
  132. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/ServerSentEventsTransport.js +90 -105
  133. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Subject.js +30 -35
  134. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/TextMessageFormat.js +16 -21
  135. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Utils.js +215 -248
  136. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/WebSocketTransport.js +135 -157
  137. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/XhrHttpClient.js +76 -85
  138. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/index.js +24 -27
  139. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/pkg-version.js +3 -4
  140. package/dist/cjs/pathfinding/Pathfinding.js +245 -263
  141. package/dist/cjs/performance/AssetStreaming.js +561 -635
  142. package/dist/cjs/performance/BenchmarkSuite.js +283 -311
  143. package/dist/cjs/performance/DeltaCompression.js +467 -526
  144. package/dist/cjs/performance/DeterministicPhysics.js +450 -498
  145. package/dist/cjs/performance/ECSOptimization.js +644 -695
  146. package/dist/cjs/performance/GameSaveSystem.js +509 -556
  147. package/dist/cjs/performance/HotReload.js +447 -500
  148. package/dist/cjs/performance/InputRecording.js +511 -561
  149. package/dist/cjs/performance/InterestManagement.js +453 -500
  150. package/dist/cjs/performance/LocalizationRuntime.js +376 -423
  151. package/dist/cjs/performance/MemoryManagement.js +410 -470
  152. package/dist/cjs/performance/ModSupport.js +445 -496
  153. package/dist/cjs/performance/MultiThreadedPhysics.js +400 -443
  154. package/dist/cjs/performance/NetworkPrediction.js +424 -482
  155. package/dist/cjs/performance/ObjectPooling.js +569 -617
  156. package/dist/cjs/performance/Performance.js +174 -190
  157. package/dist/cjs/performance/PerformanceAdvanced.js +614 -637
  158. package/dist/cjs/performance/WebGPURenderer.js +656 -683
  159. package/dist/cjs/physics/PhysicsAdvanced.js +345 -379
  160. package/dist/cjs/physics/PhysicsEngine2D.js +391 -427
  161. package/dist/cjs/plugins/PluginSDK.js +432 -466
  162. package/dist/cjs/plugins/PluginTestKit.js +307 -330
  163. package/dist/cjs/procedural/Procedural.js +243 -254
  164. package/dist/cjs/procedural/WorldBuilding.js +297 -314
  165. package/dist/cjs/quest/QuestSystem.js +975 -932
  166. package/dist/cjs/release/MobileExport.js +157 -163
  167. package/dist/cjs/release/Release.js +225 -238
  168. package/dist/cjs/rendering/Camera2D.js +121 -124
  169. package/dist/cjs/rendering/Renderer2D.js +321 -335
  170. package/dist/cjs/rendering/WebGPURenderPipeline.js +632 -651
  171. package/dist/cjs/runtime3d/Runtime3D.js +359 -378
  172. package/dist/cjs/runtime3d/SceneEditor3D.js +252 -263
  173. package/dist/cjs/scene/SceneManager.js +177 -193
  174. package/dist/cjs/scripting/GraphToAST.js +574 -547
  175. package/dist/cjs/scripting/LanguageExporter.js +254 -279
  176. package/dist/cjs/scripting/NodeGraph.js +546 -570
  177. package/dist/cjs/scripting/ScriptAST.js +31 -39
  178. package/dist/cjs/scripting/VisualScripting2.js +1016 -1065
  179. package/dist/cjs/scripting/exporters/CSharpExporter.js +464 -496
  180. package/dist/cjs/scripting/exporters/GDScriptExporter.js +390 -442
  181. package/dist/cjs/scripting/exporters/LuaExporter.js +406 -447
  182. package/dist/cjs/scripting/exporters/PythonExporter.js +484 -549
  183. package/dist/cjs/scripting/exporters/RustExporter.js +459 -512
  184. package/dist/cjs/scripting/exporters/TypeScriptExporter.js +505 -556
  185. package/dist/cjs/social/Social.js +72 -80
  186. package/dist/cjs/systems/LightingSystem.js +844 -931
  187. package/dist/cjs/systems/ParticleSystem2.js +1447 -1451
  188. package/dist/cjs/systems/PhysicsDebugSystem.js +1070 -1141
  189. package/dist/cjs/systems/TerrainSystem.js +985 -1098
  190. package/dist/cjs/templates/ActionTemplates.js +296 -309
  191. package/dist/cjs/templates/FightingTemplate.js +417 -463
  192. package/dist/cjs/templates/MetroidvaniaTemplate.js +353 -405
  193. package/dist/cjs/templates/PartyTemplates.js +190 -202
  194. package/dist/cjs/templates/PuzzleTemplates.js +245 -261
  195. package/dist/cjs/templates/RPGTemplates.js +160 -178
  196. package/dist/cjs/templates/SportsTemplates.js +237 -250
  197. package/dist/cjs/templates/StrategyTemplates.js +143 -153
  198. package/dist/cjs/templates/SurvivalTemplate.js +336 -380
  199. package/dist/cjs/templates/WaveDefense.js +499 -526
  200. package/dist/cjs/tilemap/Tilemap.js +207 -214
  201. package/dist/cjs/tutorials/TutorialBranching.js +396 -417
  202. package/dist/cjs/tutorials/TutorialEngine.js +888 -931
  203. package/dist/cjs/tutorials/TutorialOverlay.js +602 -640
  204. package/dist/cjs/tutorials/content/Tutorials_T05_T08.js +787 -809
  205. package/dist/cjs/tutorials/content/Tutorials_T09_T11.js +736 -756
  206. package/dist/cjs/tutorials/content/Tutorials_T12_T15.js +754 -778
  207. package/dist/cjs/ui/GameUI.js +295 -312
  208. package/dist/cjs/unity-integration/UnityAssetStore.js +700 -741
  209. package/dist/cjs/unity-integration/UnityImport.js +1066 -1176
  210. package/dist/cjs/unity-integration/UnityLiveLink.js +934 -981
  211. package/dist/cjs/unity-integration/components/UnityAssetStoreBrowser.js +1233 -757
  212. package/dist/cjs/unity-integration/components/UnityProjectBrowser.js +1240 -768
  213. package/dist/cjs/unreal-integration/UnrealImport.js +391 -412
  214. package/dist/cjs/unreal-integration/UnrealLiveLink.js +1102 -1137
  215. package/dist/cjs/unreal-integration/UnrealMarketplace.js +436 -473
  216. package/dist/cjs/unreal-integration/components/UnrealProjectBrowser.js +1150 -767
  217. package/dist/cjs/xr/ARVR.js +167 -175
  218. package/dist/esm/accessibility/Accessibility.js +160 -164
  219. package/dist/esm/ai/AI.js +310 -293
  220. package/dist/esm/ai/BehaviorTree.js +1057 -1112
  221. package/dist/esm/ai/StateMachine.js +709 -755
  222. package/dist/esm/animation/Animation.js +237 -240
  223. package/dist/esm/audio/AudioAdvanced.js +239 -235
  224. package/dist/esm/audio/AudioBridge.js +448 -434
  225. package/dist/esm/audio/AudioManager.js +243 -258
  226. package/dist/esm/build-cloud/BuildOrchestration.js +1071 -1097
  227. package/dist/esm/build-cloud/GodotBuildCloud.js +647 -669
  228. package/dist/esm/build-cloud/UnityBuildCloud.js +571 -609
  229. package/dist/esm/build-cloud/UnrealBuildCloud.js +615 -634
  230. package/dist/esm/core/EventBus.js +52 -55
  231. package/dist/esm/core/GameClock.js +63 -65
  232. package/dist/esm/core/GameConfig.js +77 -78
  233. package/dist/esm/core/GameLoop.js +81 -88
  234. package/dist/esm/core/ServiceLocator.js +63 -64
  235. package/dist/esm/core/Validation.js +82 -81
  236. package/dist/esm/core/math.js +109 -111
  237. package/dist/esm/devtools/DevTools.js +546 -562
  238. package/dist/esm/devtools/DeveloperExperience.js +535 -558
  239. package/dist/esm/devtools/GameplayAnalytics.js +647 -645
  240. package/dist/esm/dialogue/DialogueSystem.js +998 -985
  241. package/dist/esm/docs/DocGenerator.js +342 -363
  242. package/dist/esm/ecs/World.js +358 -370
  243. package/dist/esm/editor/AchievementEditor.js +584 -635
  244. package/dist/esm/editor/AdvancedEditor.js +191 -190
  245. package/dist/esm/editor/AnimationRetargeting.js +700 -740
  246. package/dist/esm/editor/AssetBrowser.js +1078 -1159
  247. package/dist/esm/editor/AssetManager.js +188 -191
  248. package/dist/esm/editor/ConsolePro.js +977 -1060
  249. package/dist/esm/editor/CraftingEditor.js +684 -729
  250. package/dist/esm/editor/DebugTools.js +194 -184
  251. package/dist/esm/editor/DialogueSystem.js +849 -900
  252. package/dist/esm/editor/LeaderboardSystem.js +433 -482
  253. package/dist/esm/editor/NiceGameEditor.js +1908 -1200
  254. package/dist/esm/editor/PrefabSystem.js +777 -837
  255. package/dist/esm/editor/ProfilerPanel.js +654 -699
  256. package/dist/esm/editor/QuestEditor.js +795 -838
  257. package/dist/esm/editor/ReplaySystem.js +591 -633
  258. package/dist/esm/editor/SceneEditor.js +189 -199
  259. package/dist/esm/editor/ScreenshotMode.js +628 -687
  260. package/dist/esm/editor/ShaderGraph.js +1565 -1581
  261. package/dist/esm/editor/TimelineEditor.js +733 -777
  262. package/dist/esm/editor/UndoRedoPro.js +835 -903
  263. package/dist/esm/editor/VRARMode.js +586 -644
  264. package/dist/esm/engine/NiceGameEngine.js +142 -163
  265. package/dist/esm/engine/SaveSystem.js +447 -494
  266. package/dist/esm/enterprise/Enterprise.js +265 -260
  267. package/dist/esm/export/BevyExporter.js +929 -966
  268. package/dist/esm/export/CocosExporter.js +646 -672
  269. package/dist/esm/export/Construct3Exporter.js +785 -793
  270. package/dist/esm/export/DefoldExporter.js +1030 -1068
  271. package/dist/esm/export/GDevelopExporter.js +676 -707
  272. package/dist/esm/export/GameMakerExporter.js +793 -804
  273. package/dist/esm/export/GodotExporter.js +1004 -1044
  274. package/dist/esm/export/MinecraftBedrockExporter.js +575 -577
  275. package/dist/esm/export/MonoGameExporter.js +1267 -1292
  276. package/dist/esm/export/Pico8Exporter.js +768 -811
  277. package/dist/esm/export/PlatformExporter.js +193 -205
  278. package/dist/esm/export/RPGMakerExporter.js +862 -878
  279. package/dist/esm/export/RobloxExporter.js +885 -918
  280. package/dist/esm/export/Solar2DExporter.js +1220 -1255
  281. package/dist/esm/export/ThreeJSExporter.js +1007 -1072
  282. package/dist/esm/export/Tic80Exporter.js +1212 -1266
  283. package/dist/esm/export/UnityExporter.js +1117 -1130
  284. package/dist/esm/export/UnrealExporter.js +891 -918
  285. package/dist/esm/export/WebExporter.js +933 -969
  286. package/dist/esm/export/index.js +86 -71
  287. package/dist/esm/godot-integration/GodotAssetLibrary.js +663 -691
  288. package/dist/esm/godot-integration/GodotImport.js +935 -1026
  289. package/dist/esm/godot-integration/GodotLiveLink.js +918 -944
  290. package/dist/esm/godot-integration/components/GodotProjectBrowser.js +912 -610
  291. package/dist/esm/i18n/I18n.js +871 -899
  292. package/dist/esm/i18n/useTranslation.js +88 -88
  293. package/dist/esm/import/AsepriteImporter.js +637 -715
  294. package/dist/esm/import/DragonBonesImporter.js +417 -460
  295. package/dist/esm/import/GameMakerImporter.js +491 -520
  296. package/dist/esm/import/GodotSceneImporter.js +767 -821
  297. package/dist/esm/import/LDtkImporter.js +415 -453
  298. package/dist/esm/import/Live2DImporter.js +477 -517
  299. package/dist/esm/import/NdgFormat.js +410 -456
  300. package/dist/esm/import/OgmoImporter.js +446 -492
  301. package/dist/esm/import/RPGMakerImporter.js +431 -476
  302. package/dist/esm/import/SceneImporter.js +385 -422
  303. package/dist/esm/import/SpineImporter.js +491 -545
  304. package/dist/esm/import/SpriterImporter.js +570 -612
  305. package/dist/esm/import/TiledMapImporter.js +790 -845
  306. package/dist/esm/import/UnitySceneImporter.js +666 -702
  307. package/dist/esm/import/index.js +247 -258
  308. package/dist/esm/index.js +1332 -188
  309. package/dist/esm/input/GamepadNavigation.js +187 -204
  310. package/dist/esm/input/InputManager.js +401 -420
  311. package/dist/esm/input/useGamepads.js +72 -80
  312. package/dist/esm/integration/IconSprite.js +143 -255
  313. package/dist/esm/inventory/InventorySystem.js +925 -994
  314. package/dist/esm/kids/KidMode.js +1003 -1021
  315. package/dist/esm/kids/KidTools.js +573 -593
  316. package/dist/esm/monetization/Monetization.js +180 -176
  317. package/dist/esm/multiplayer/LocalMultiplayer.js +290 -286
  318. package/dist/esm/multiplayer/MiniGameTypes.js +58 -58
  319. package/dist/esm/native-engine/AnimationSystem.js +735 -805
  320. package/dist/esm/native-engine/AssetPipeline.js +456 -514
  321. package/dist/esm/native-engine/AudioEngine.js +765 -803
  322. package/dist/esm/native-engine/InputSystem.js +1079 -1144
  323. package/dist/esm/native-engine/NetworkingSystem.js +740 -792
  324. package/dist/esm/native-engine/PhysicsEngine.js +585 -606
  325. package/dist/esm/native-engine/RenderingEngine.js +304 -349
  326. package/dist/esm/native-engine/SceneGraph.js +773 -807
  327. package/dist/esm/network/MultiplayerTransport.js +99 -131
  328. package/dist/esm/network/Networking.js +556 -563
  329. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/AbortController.js +22 -28
  330. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/AccessTokenHttpClient.js +41 -47
  331. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/DefaultHttpClient.js +36 -42
  332. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/DefaultReconnectPolicy.js +11 -14
  333. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Errors.js +111 -134
  334. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/FetchHttpClient.js +132 -157
  335. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HandshakeProtocol.js +40 -52
  336. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HeaderNames.js +6 -7
  337. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HttpClient.js +42 -47
  338. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HttpConnection.js +496 -571
  339. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HubConnection.js +828 -952
  340. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HubConnectionBuilder.js +126 -145
  341. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/IHubProtocol.js +14 -23
  342. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/ILogger.js +12 -25
  343. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/ITransport.js +15 -24
  344. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/JsonHubProtocol.js +109 -120
  345. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Loggers.js +11 -13
  346. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/LongPollingTransport.js +151 -184
  347. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/MessageBuffer.js +159 -195
  348. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/ServerSentEventsTransport.js +91 -104
  349. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Subject.js +31 -34
  350. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/TextMessageFormat.js +17 -20
  351. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Utils.js +230 -248
  352. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/WebSocketTransport.js +136 -156
  353. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/XhrHttpClient.js +77 -84
  354. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/index.js +31 -12
  355. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/pkg-version.js +4 -3
  356. package/dist/esm/pathfinding/Pathfinding.js +249 -262
  357. package/dist/esm/performance/AssetStreaming.js +567 -634
  358. package/dist/esm/performance/BenchmarkSuite.js +285 -310
  359. package/dist/esm/performance/DeltaCompression.js +478 -525
  360. package/dist/esm/performance/DeterministicPhysics.js +479 -497
  361. package/dist/esm/performance/ECSOptimization.js +653 -694
  362. package/dist/esm/performance/GameSaveSystem.js +515 -555
  363. package/dist/esm/performance/HotReload.js +454 -499
  364. package/dist/esm/performance/InputRecording.js +520 -560
  365. package/dist/esm/performance/InterestManagement.js +460 -499
  366. package/dist/esm/performance/LocalizationRuntime.js +382 -422
  367. package/dist/esm/performance/MemoryManagement.js +415 -469
  368. package/dist/esm/performance/ModSupport.js +455 -495
  369. package/dist/esm/performance/MultiThreadedPhysics.js +408 -442
  370. package/dist/esm/performance/NetworkPrediction.js +436 -481
  371. package/dist/esm/performance/ObjectPooling.js +582 -616
  372. package/dist/esm/performance/Performance.js +182 -189
  373. package/dist/esm/performance/PerformanceAdvanced.js +621 -636
  374. package/dist/esm/performance/WebGPURenderer.js +660 -682
  375. package/dist/esm/physics/PhysicsAdvanced.js +359 -378
  376. package/dist/esm/physics/PhysicsEngine2D.js +393 -426
  377. package/dist/esm/plugins/PluginSDK.js +435 -465
  378. package/dist/esm/plugins/PluginTestKit.js +315 -329
  379. package/dist/esm/procedural/Procedural.js +248 -253
  380. package/dist/esm/procedural/WorldBuilding.js +316 -313
  381. package/dist/esm/quest/QuestSystem.js +982 -931
  382. package/dist/esm/release/MobileExport.js +163 -162
  383. package/dist/esm/release/Release.js +234 -237
  384. package/dist/esm/rendering/Camera2D.js +122 -123
  385. package/dist/esm/rendering/Renderer2D.js +323 -334
  386. package/dist/esm/rendering/WebGPURenderPipeline.js +647 -650
  387. package/dist/esm/runtime3d/Runtime3D.js +368 -377
  388. package/dist/esm/runtime3d/SceneEditor3D.js +268 -262
  389. package/dist/esm/scene/SceneManager.js +178 -192
  390. package/dist/esm/scripting/GraphToAST.js +576 -546
  391. package/dist/esm/scripting/LanguageExporter.js +263 -278
  392. package/dist/esm/scripting/NodeGraph.js +550 -569
  393. package/dist/esm/scripting/ScriptAST.js +45 -38
  394. package/dist/esm/scripting/VisualScripting2.js +1025 -1064
  395. package/dist/esm/scripting/exporters/CSharpExporter.js +465 -495
  396. package/dist/esm/scripting/exporters/GDScriptExporter.js +391 -441
  397. package/dist/esm/scripting/exporters/LuaExporter.js +407 -446
  398. package/dist/esm/scripting/exporters/PythonExporter.js +485 -548
  399. package/dist/esm/scripting/exporters/RustExporter.js +460 -511
  400. package/dist/esm/scripting/exporters/TypeScriptExporter.js +506 -555
  401. package/dist/esm/social/Social.js +77 -79
  402. package/dist/esm/systems/LightingSystem.js +855 -930
  403. package/dist/esm/systems/ParticleSystem2.js +1453 -1450
  404. package/dist/esm/systems/PhysicsDebugSystem.js +1078 -1140
  405. package/dist/esm/systems/TerrainSystem.js +996 -1097
  406. package/dist/esm/templates/ActionTemplates.js +307 -308
  407. package/dist/esm/templates/FightingTemplate.js +439 -462
  408. package/dist/esm/templates/MetroidvaniaTemplate.js +391 -404
  409. package/dist/esm/templates/PartyTemplates.js +206 -201
  410. package/dist/esm/templates/PuzzleTemplates.js +260 -260
  411. package/dist/esm/templates/RPGTemplates.js +172 -177
  412. package/dist/esm/templates/SportsTemplates.js +251 -249
  413. package/dist/esm/templates/StrategyTemplates.js +158 -152
  414. package/dist/esm/templates/SurvivalTemplate.js +367 -379
  415. package/dist/esm/templates/WaveDefense.js +501 -525
  416. package/dist/esm/tilemap/Tilemap.js +209 -213
  417. package/dist/esm/tutorials/TutorialBranching.js +399 -416
  418. package/dist/esm/tutorials/TutorialEngine.js +893 -930
  419. package/dist/esm/tutorials/TutorialOverlay.js +603 -639
  420. package/dist/esm/tutorials/content/Tutorials_T05_T08.js +792 -808
  421. package/dist/esm/tutorials/content/Tutorials_T09_T11.js +740 -755
  422. package/dist/esm/tutorials/content/Tutorials_T12_T15.js +759 -777
  423. package/dist/esm/ui/GameUI.js +296 -311
  424. package/dist/esm/unity-integration/UnityAssetStore.js +704 -740
  425. package/dist/esm/unity-integration/UnityImport.js +1071 -1175
  426. package/dist/esm/unity-integration/UnityLiveLink.js +938 -980
  427. package/dist/esm/unity-integration/components/UnityAssetStoreBrowser.js +1234 -756
  428. package/dist/esm/unity-integration/components/UnityProjectBrowser.js +1241 -767
  429. package/dist/esm/unreal-integration/UnrealImport.js +395 -411
  430. package/dist/esm/unreal-integration/UnrealLiveLink.js +1105 -1136
  431. package/dist/esm/unreal-integration/UnrealMarketplace.js +442 -472
  432. package/dist/esm/unreal-integration/components/UnrealProjectBrowser.js +1151 -766
  433. package/dist/esm/xr/ARVR.js +181 -174
  434. package/package.json +7 -12
@@ -1,1124 +1,1023 @@
1
- /**
2
- * @file TerrainSystem.ts
3
- * @description Advanced Terrain System with Heightmap, Splatmap, and Foliage
4
- * PRO-1.4: Professional Editor Features
5
- *
6
- * Features:
7
- * - Heightmap terrain with LOD
8
- * - Splatmap texture blending (up to 8 layers)
9
- * - Foliage scattering (grass, trees, rocks)
10
- * - Terrain brushes (raise, lower, smooth, flatten, noise, erosion)
11
- * - Procedural generation (Perlin noise, diamond-square, hydraulic erosion)
12
- * - Holes/caves support
13
- * - Detail meshes and decals
14
- * - Terrain chunks with streaming
15
- * - Physics collision mesh generation
16
- */
17
1
  const DEFAULT_TERRAIN_CONFIG = {
18
- width: 1000,
19
- depth: 1000,
20
- maxHeight: 100,
21
- heightmapResolution: 513, // Power of 2 + 1 for LOD
22
- splatmapResolution: 512,
23
- chunksPerSide: 4,
24
- detailResolution: 1024,
25
- detailResolutionPerPatch: 8,
26
- basemapDistance: 1000,
27
- castShadows: true,
28
- drawInstanced: true,
2
+ width: 1e3,
3
+ depth: 1e3,
4
+ maxHeight: 100,
5
+ heightmapResolution: 513,
6
+ // Power of 2 + 1 for LOD
7
+ splatmapResolution: 512,
8
+ chunksPerSide: 4,
9
+ detailResolution: 1024,
10
+ detailResolutionPerPatch: 8,
11
+ basemapDistance: 1e3,
12
+ castShadows: true,
13
+ drawInstanced: true
29
14
  };
30
15
  function createTerrainLayer(id, name, diffuseTexture) {
31
- return {
32
- id,
33
- name,
34
- diffuseTexture,
35
- tileSize: { x: 15, y: 15 },
36
- tileOffset: { x: 0, y: 0 },
37
- metallic: 0,
38
- smoothness: 0.5,
39
- specularColor: { r: 0.2, g: 0.2, b: 0.2, a: 1 },
40
- normalScale: 1,
41
- diffuseRemapMin: { r: 0, g: 0, b: 0, a: 0 },
42
- diffuseRemapMax: { r: 1, g: 1, b: 1, a: 1 },
43
- maskRemapMin: { r: 0, g: 0, b: 0, a: 0 },
44
- maskRemapMax: { r: 1, g: 1, b: 1, a: 1 },
45
- };
16
+ return {
17
+ id,
18
+ name,
19
+ diffuseTexture,
20
+ tileSize: { x: 15, y: 15 },
21
+ tileOffset: { x: 0, y: 0 },
22
+ metallic: 0,
23
+ smoothness: 0.5,
24
+ specularColor: { r: 0.2, g: 0.2, b: 0.2, a: 1 },
25
+ normalScale: 1,
26
+ diffuseRemapMin: { r: 0, g: 0, b: 0, a: 0 },
27
+ diffuseRemapMax: { r: 1, g: 1, b: 1, a: 1 },
28
+ maskRemapMin: { r: 0, g: 0, b: 0, a: 0 },
29
+ maskRemapMax: { r: 1, g: 1, b: 1, a: 1 }
30
+ };
46
31
  }
47
32
  function createGrassDetail(id, name, textureId) {
48
- return {
49
- id,
50
- name,
51
- textureId,
52
- renderMode: 'grass',
53
- useInstancing: true,
54
- healthyColor: { r: 0.26, g: 0.8, b: 0.28, a: 1 },
55
- dryColor: { r: 0.8, g: 0.72, b: 0.28, a: 1 },
56
- minWidth: 0.8,
57
- maxWidth: 1.2,
58
- minHeight: 0.4,
59
- maxHeight: 0.8,
60
- noiseSpread: 0.1,
61
- density: 1,
62
- alignToGround: 0.5,
63
- positionJitter: 0.5,
64
- holeEdgePadding: 0,
65
- };
33
+ return {
34
+ id,
35
+ name,
36
+ textureId,
37
+ renderMode: "grass",
38
+ useInstancing: true,
39
+ healthyColor: { r: 0.26, g: 0.8, b: 0.28, a: 1 },
40
+ dryColor: { r: 0.8, g: 0.72, b: 0.28, a: 1 },
41
+ minWidth: 0.8,
42
+ maxWidth: 1.2,
43
+ minHeight: 0.4,
44
+ maxHeight: 0.8,
45
+ noiseSpread: 0.1,
46
+ density: 1,
47
+ alignToGround: 0.5,
48
+ positionJitter: 0.5,
49
+ holeEdgePadding: 0
50
+ };
66
51
  }
67
52
  function createTreePrototype(id, name, meshId) {
68
- return {
69
- id,
70
- name,
71
- meshId,
72
- lodMeshes: [],
73
- bendFactor: 1,
74
- minScale: 0.8,
75
- maxScale: 1.2,
76
- randomRotation: true,
77
- alignToGround: 0.5,
78
- navMeshArea: 0,
79
- };
53
+ return {
54
+ id,
55
+ name,
56
+ meshId,
57
+ lodMeshes: [],
58
+ bendFactor: 1,
59
+ minScale: 0.8,
60
+ maxScale: 1.2,
61
+ randomRotation: true,
62
+ alignToGround: 0.5,
63
+ navMeshArea: 0
64
+ };
80
65
  }
81
66
  const DEFAULT_BRUSH = {
82
- type: 'raise',
83
- size: 10,
84
- strength: 0.5,
85
- falloff: 0.5,
86
- rotation: 0,
87
- spacingJitter: 0,
88
- scatter: 0,
67
+ type: "raise",
68
+ size: 10,
69
+ strength: 0.5,
70
+ falloff: 0.5,
71
+ rotation: 0,
72
+ spacingJitter: 0,
73
+ scatter: 0
89
74
  };
90
- // ============================================================
91
- // Terrain System Class
92
- // ============================================================
93
75
  class TerrainSystem {
94
- constructor(config) {
95
- this.undoStack = [];
96
- this.redoStack = [];
97
- this.maxUndoSteps = 50;
98
- this.data = this.createEmptyTerrain(config);
99
- }
100
- createEmptyTerrain(configOverride) {
101
- const config = { ...DEFAULT_TERRAIN_CONFIG, ...configOverride };
102
- const hmRes = config.heightmapResolution;
103
- const smRes = config.splatmapResolution;
104
- config.detailResolution;
105
- const chunks = config.chunksPerSide;
106
- // Initialize heightmap
107
- const heightmap = new Float32Array(hmRes * hmRes);
108
- // Initialize splatmaps (2 textures for 8 layers)
109
- const splatmaps = [
110
- new Uint8Array(smRes * smRes * 4),
111
- new Uint8Array(smRes * smRes * 4),
112
- ];
113
- // Set first layer to full coverage by default
114
- for (let i = 0; i < smRes * smRes; i++) {
115
- splatmaps[0][i * 4] = 255; // Layer 0 = 100%
116
- }
117
- // Initialize holemap (all solid)
118
- const holemap = new Uint8Array(hmRes * hmRes);
119
- holemap.fill(1);
120
- // Create chunks
121
- const chunkList = [];
122
- const chunkWidth = config.width / chunks;
123
- const chunkDepth = config.depth / chunks;
124
- for (let gz = 0; gz < chunks; gz++) {
125
- for (let gx = 0; gx < chunks; gx++) {
126
- chunkList.push({
127
- id: `chunk_${gx}_${gz}`,
128
- gridX: gx,
129
- gridZ: gz,
130
- boundsMin: {
131
- x: gx * chunkWidth - config.width / 2,
132
- y: 0,
133
- z: gz * chunkDepth - config.depth / 2,
134
- },
135
- boundsMax: {
136
- x: (gx + 1) * chunkWidth - config.width / 2,
137
- y: config.maxHeight,
138
- z: (gz + 1) * chunkDepth - config.depth / 2,
139
- },
140
- isLoaded: gx < 2 && gz < 2, // Load center chunks
141
- lodLevel: 0,
142
- });
143
- }
144
- }
145
- return {
146
- id: `terrain_${Date.now()}`,
147
- name: 'New Terrain',
148
- config,
149
- heightmap,
150
- splatmaps,
151
- holemap,
152
- layers: [],
153
- detailPrototypes: [],
154
- detailMaps: [],
155
- treePrototypes: [],
156
- trees: [],
157
- chunks: chunkList,
158
- metadata: {
159
- createdAt: Date.now(),
160
- modifiedAt: Date.now(),
161
- version: 1,
162
- },
163
- };
164
- }
165
- // ─── Heightmap Operations ──────────────────────────────
166
- /** Get height at grid coordinates (0 to resolution-1) */
167
- getHeightAtGrid(gridX, gridZ) {
168
- const res = this.data.config.heightmapResolution;
169
- const x = Math.max(0, Math.min(res - 1, Math.floor(gridX)));
170
- const z = Math.max(0, Math.min(res - 1, Math.floor(gridZ)));
171
- return this.data.heightmap[z * res + x] * this.data.config.maxHeight;
172
- }
173
- /** Set height at grid coordinates */
174
- setHeightAtGrid(gridX, gridZ, height, recordUndo = true) {
175
- const res = this.data.config.heightmapResolution;
176
- const maxH = this.data.config.maxHeight;
177
- if (gridX < 0 || gridX >= res || gridZ < 0 || gridZ >= res) {
178
- return;
179
- }
180
- const idx = gridZ * res + gridX;
181
- const normalizedHeight = Math.max(0, Math.min(1, height / maxH));
182
- if (recordUndo) {
183
- this.recordHeightChange(gridX, gridZ, this.data.heightmap[idx], normalizedHeight);
184
- }
185
- this.data.heightmap[idx] = normalizedHeight;
186
- this.data.metadata.modifiedAt = Date.now();
187
- }
188
- /** Get interpolated height at world coordinates */
189
- getHeightAtWorld(worldX, worldZ) {
190
- const { width, depth, heightmapResolution: res } = this.data.config;
191
- // Convert world to grid
192
- const gx = ((worldX + width / 2) / width) * (res - 1);
193
- const gz = ((worldZ + depth / 2) / depth) * (res - 1);
194
- // Bilinear interpolation
195
- const ix = Math.floor(gx);
196
- const iz = Math.floor(gz);
197
- const fx = gx - ix;
198
- const fz = gz - iz;
199
- const h00 = this.getHeightAtGrid(ix, iz);
200
- const h10 = this.getHeightAtGrid(ix + 1, iz);
201
- const h01 = this.getHeightAtGrid(ix, iz + 1);
202
- const h11 = this.getHeightAtGrid(ix + 1, iz + 1);
203
- const h0 = h00 + (h10 - h00) * fx;
204
- const h1 = h01 + (h11 - h01) * fx;
205
- return h0 + (h1 - h0) * fz;
206
- }
207
- /** Convert world position to grid coordinates */
208
- worldToGrid(worldX, worldZ) {
209
- const { width, depth, heightmapResolution: res } = this.data.config;
210
- return {
211
- x: ((worldX + width / 2) / width) * (res - 1),
212
- y: ((worldZ + depth / 2) / depth) * (res - 1),
213
- };
214
- }
215
- /** Convert grid coordinates to world position */
216
- gridToWorld(gridX, gridZ) {
217
- const { width, depth, heightmapResolution: res } = this.data.config;
218
- const worldX = (gridX / (res - 1)) * width - width / 2;
219
- const worldZ = (gridZ / (res - 1)) * depth - depth / 2;
220
- const worldY = this.getHeightAtGrid(gridX, gridZ);
221
- return { x: worldX, y: worldY, z: worldZ };
222
- }
223
- /// Get terrain normal at world position
224
- getNormalAtWorld(worldX, worldZ) {
225
- const { width, depth, heightmapResolution: res } = this.data.config;
226
- const cellWidth = width / (res - 1);
227
- const cellDepth = depth / (res - 1);
228
- const hL = this.getHeightAtWorld(worldX - cellWidth, worldZ);
229
- const hR = this.getHeightAtWorld(worldX + cellWidth, worldZ);
230
- const hD = this.getHeightAtWorld(worldX, worldZ - cellDepth);
231
- const hU = this.getHeightAtWorld(worldX, worldZ + cellDepth);
232
- // Cross product to get normal
233
- const dx = hR - hL;
234
- const dz = hU - hD;
235
- const nx = -dx / (2 * cellWidth);
236
- const ny = 1;
237
- const nz = -dz / (2 * cellDepth);
238
- // Normalize
239
- const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
240
- return { x: nx / len, y: ny / len, z: nz / len };
241
- }
242
- // ─── Brush Operations ──────────────────────────────────
243
- applyBrush(brush, worldX, worldZ) {
244
- switch (brush.type) {
245
- case 'raise':
246
- this.applyHeightBrush(worldX, worldZ, brush, 1);
247
- break;
248
- case 'lower':
249
- this.applyHeightBrush(worldX, worldZ, brush, -1);
250
- break;
251
- case 'flatten':
252
- this.applyFlattenBrush(worldX, worldZ, brush);
253
- break;
254
- case 'smooth':
255
- this.applySmoothBrush(worldX, worldZ, brush);
256
- break;
257
- case 'noise':
258
- this.applyNoiseBrush(worldX, worldZ, brush);
259
- break;
260
- case 'erosion':
261
- this.applyErosionBrush(worldX, worldZ, brush);
262
- break;
263
- case 'paint':
264
- this.applyPaintBrush(worldX, worldZ, brush);
265
- break;
266
- case 'paintHoles':
267
- this.applyHoleBrush(worldX, worldZ, brush);
268
- break;
269
- case 'stampHeight':
270
- this.applyStampBrush(worldX, worldZ, brush);
271
- break;
272
- }
273
- }
274
- applyHeightBrush(worldX, worldZ, brush, direction) {
275
- const grid = this.worldToGrid(worldX, worldZ);
276
- const { heightmapResolution: res, width, maxHeight } = this.data.config;
277
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
278
- const delta = (brush.strength * direction * maxHeight) / 100;
279
- const minX = Math.max(0, Math.floor(grid.x - gridRadius));
280
- const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
281
- const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
282
- const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
283
- for (let gz = minZ; gz <= maxZ; gz++) {
284
- for (let gx = minX; gx <= maxX; gx++) {
285
- const dx = gx - grid.x;
286
- const dz = gz - grid.y;
287
- const dist = Math.sqrt(dx * dx + dz * dz);
288
- if (dist <= gridRadius) {
289
- const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
290
- const currentHeight = this.getHeightAtGrid(gx, gz);
291
- const newHeight = currentHeight + delta * falloff;
292
- this.setHeightAtGrid(gx, gz, newHeight);
293
- }
294
- }
295
- }
296
- }
297
- applyFlattenBrush(worldX, worldZ, brush) {
298
- const grid = this.worldToGrid(worldX, worldZ);
299
- const { heightmapResolution: res, width } = this.data.config;
300
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
301
- const targetHeight = brush.targetHeight ?? this.getHeightAtWorld(worldX, worldZ);
302
- const minX = Math.max(0, Math.floor(grid.x - gridRadius));
303
- const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
304
- const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
305
- const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
306
- for (let gz = minZ; gz <= maxZ; gz++) {
307
- for (let gx = minX; gx <= maxX; gx++) {
308
- const dx = gx - grid.x;
309
- const dz = gz - grid.y;
310
- const dist = Math.sqrt(dx * dx + dz * dz);
311
- if (dist <= gridRadius) {
312
- const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
313
- const currentHeight = this.getHeightAtGrid(gx, gz);
314
- const newHeight = currentHeight + (targetHeight - currentHeight) * falloff * brush.strength;
315
- this.setHeightAtGrid(gx, gz, newHeight);
316
- }
317
- }
318
- }
319
- }
320
- applySmoothBrush(worldX, worldZ, brush) {
321
- const grid = this.worldToGrid(worldX, worldZ);
322
- const { heightmapResolution: res, width } = this.data.config;
323
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
324
- const minX = Math.max(0, Math.floor(grid.x - gridRadius));
325
- const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
326
- const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
327
- const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
328
- // Collect heights first
329
- const newHeights = [];
330
- for (let gz = minZ; gz <= maxZ; gz++) {
331
- for (let gx = minX; gx <= maxX; gx++) {
332
- const dx = gx - grid.x;
333
- const dz = gz - grid.y;
334
- const dist = Math.sqrt(dx * dx + dz * dz);
335
- if (dist <= gridRadius) {
336
- // Average of neighbors
337
- let sum = 0;
338
- let count = 0;
339
- for (let nz = -1; nz <= 1; nz++) {
340
- for (let nx = -1; nx <= 1; nx++) {
341
- const ngx = gx + nx;
342
- const ngz = gz + nz;
343
- if (ngx >= 0 && ngx < res && ngz >= 0 && ngz < res) {
344
- sum += this.getHeightAtGrid(ngx, ngz);
345
- count++;
346
- }
347
- }
348
- }
349
- const avgHeight = sum / count;
350
- const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
351
- const currentHeight = this.getHeightAtGrid(gx, gz);
352
- const newHeight = currentHeight + (avgHeight - currentHeight) * falloff * brush.strength;
353
- newHeights.push({ gx, gz, height: newHeight });
354
- }
355
- }
356
- }
357
- // Apply new heights
358
- for (const { gx, gz, height } of newHeights) {
359
- this.setHeightAtGrid(gx, gz, height);
360
- }
361
- }
362
- applyNoiseBrush(worldX, worldZ, brush) {
363
- const grid = this.worldToGrid(worldX, worldZ);
364
- const { heightmapResolution: res, width, maxHeight } = this.data.config;
365
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
366
- const noiseScale = brush.noiseScale ?? 0.1;
367
- const octaves = brush.noiseOctaves ?? 4;
368
- const minX = Math.max(0, Math.floor(grid.x - gridRadius));
369
- const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
370
- const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
371
- const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
372
- for (let gz = minZ; gz <= maxZ; gz++) {
373
- for (let gx = minX; gx <= maxX; gx++) {
374
- const dx = gx - grid.x;
375
- const dz = gz - grid.y;
376
- const dist = Math.sqrt(dx * dx + dz * dz);
377
- if (dist <= gridRadius) {
378
- const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
379
- const noise = this.perlinNoise2D(gx * noiseScale, gz * noiseScale, octaves);
380
- const delta = noise * brush.strength * maxHeight * 0.1 * falloff;
381
- const currentHeight = this.getHeightAtGrid(gx, gz);
382
- this.setHeightAtGrid(gx, gz, currentHeight + delta);
383
- }
384
- }
385
- }
386
- }
387
- applyErosionBrush(worldX, worldZ, brush) {
388
- const grid = this.worldToGrid(worldX, worldZ);
389
- const { heightmapResolution: res, width } = this.data.config;
390
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
391
- const minX = Math.max(1, Math.floor(grid.x - gridRadius));
392
- const maxX = Math.min(res - 2, Math.ceil(grid.x + gridRadius));
393
- const minZ = Math.max(1, Math.floor(grid.y - gridRadius));
394
- const maxZ = Math.min(res - 2, Math.ceil(grid.y + gridRadius));
395
- // Simple thermal erosion
396
- const newHeights = [];
397
- const talusAngle = 0.5; // Adjustment factor
398
- for (let gz = minZ; gz <= maxZ; gz++) {
399
- for (let gx = minX; gx <= maxX; gx++) {
400
- const dx = gx - grid.x;
401
- const dz = gz - grid.y;
402
- const dist = Math.sqrt(dx * dx + dz * dz);
403
- if (dist <= gridRadius) {
404
- const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
405
- const h = this.getHeightAtGrid(gx, gz);
406
- let totalDiff = 0;
407
- const neighbors = [
408
- this.getHeightAtGrid(gx - 1, gz),
409
- this.getHeightAtGrid(gx + 1, gz),
410
- this.getHeightAtGrid(gx, gz - 1),
411
- this.getHeightAtGrid(gx, gz + 1),
412
- ];
413
- for (const nh of neighbors) {
414
- const diff = h - nh;
415
- if (diff > talusAngle) {
416
- totalDiff += diff - talusAngle;
417
- }
418
- }
419
- // Erode if slope too steep
420
- if (totalDiff > 0) {
421
- const erosion = totalDiff * brush.strength * falloff * 0.25;
422
- newHeights.push({ gx, gz, height: h - erosion });
423
- }
424
- }
425
- }
426
- }
427
- // Apply erosion
428
- for (const { gx, gz, height } of newHeights) {
429
- this.setHeightAtGrid(gx, gz, height);
430
- }
431
- }
432
- applyPaintBrush(worldX, worldZ, brush) {
433
- const { splatmapResolution: res, width } = this.data.config;
434
- const layerIndex = brush.layerIndex ?? 0;
435
- if (layerIndex >= 8) {
436
- return;
437
- }
438
- const splatmapIndex = Math.floor(layerIndex / 4);
439
- const channelIndex = layerIndex % 4;
440
- // Convert world to splatmap coords
441
- const smX = ((worldX + width / 2) / width) * (res - 1);
442
- const smZ = ((worldZ + width / 2) / width) * (res - 1);
443
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
444
- const minX = Math.max(0, Math.floor(smX - gridRadius));
445
- const maxX = Math.min(res - 1, Math.ceil(smX + gridRadius));
446
- const minZ = Math.max(0, Math.floor(smZ - gridRadius));
447
- const maxZ = Math.min(res - 1, Math.ceil(smZ + gridRadius));
448
- const splatmap = this.data.splatmaps[splatmapIndex];
449
- for (let z = minZ; z <= maxZ; z++) {
450
- for (let x = minX; x <= maxX; x++) {
451
- const dx = x - smX;
452
- const dz = z - smZ;
453
- const dist = Math.sqrt(dx * dx + dz * dz);
454
- if (dist <= gridRadius) {
455
- const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
456
- const idx = (z * res + x) * 4;
457
- const strength = brush.strength * falloff * 255;
458
- // Add to target channel
459
- const current = splatmap[idx + channelIndex];
460
- const newValue = Math.min(255, current + strength);
461
- splatmap[idx + channelIndex] = newValue;
462
- // Normalize all channels so they sum to 255
463
- this.normalizeSplatmapPixel(x, z);
464
- }
465
- }
466
- }
467
- this.data.metadata.modifiedAt = Date.now();
468
- }
469
- normalizeSplatmapPixel(x, z) {
470
- const res = this.data.config.splatmapResolution;
471
- let total = 0;
472
- // Sum all 8 channels
473
- for (let s = 0; s < 2; s++) {
474
- const idx = (z * res + x) * 4;
475
- for (let c = 0; c < 4; c++) {
476
- total += this.data.splatmaps[s][idx + c];
477
- }
478
- }
479
- // Normalize
480
- if (total > 0) {
481
- const scale = 255 / total;
482
- for (let s = 0; s < 2; s++) {
483
- const idx = (z * res + x) * 4;
484
- for (let c = 0; c < 4; c++) {
485
- this.data.splatmaps[s][idx + c] = Math.round(this.data.splatmaps[s][idx + c] * scale);
486
- }
487
- }
488
- }
489
- }
490
- applyHoleBrush(worldX, worldZ, brush) {
491
- const { heightmapResolution: res, width } = this.data.config;
492
- const gridCoords = this.worldToGrid(worldX, worldZ);
493
- const gridRadius = (brush.size / (width / (res - 1))) * 0.5;
494
- const isAddHole = brush.strength > 0;
495
- const minX = Math.max(0, Math.floor(gridCoords.x - gridRadius));
496
- const maxX = Math.min(res - 1, Math.ceil(gridCoords.x + gridRadius));
497
- const minZ = Math.max(0, Math.floor(gridCoords.y - gridRadius));
498
- const maxZ = Math.min(res - 1, Math.ceil(gridCoords.y + gridRadius));
499
- for (let gz = minZ; gz <= maxZ; gz++) {
500
- for (let gx = minX; gx <= maxX; gx++) {
501
- const dx = gx - gridCoords.x;
502
- const dz = gz - gridCoords.y;
503
- const dist = Math.sqrt(dx * dx + dz * dz);
504
- if (dist <= gridRadius) {
505
- this.data.holemap[gz * res + gx] = isAddHole ? 0 : 1;
506
- }
507
- }
508
- }
509
- this.data.metadata.modifiedAt = Date.now();
510
- }
511
- applyStampBrush(worldX, worldZ, brush) {
512
- // TODO: Apply stamp texture as height
513
- // For now, just raise
514
- this.applyHeightBrush(worldX, worldZ, brush, 1);
515
- }
516
- calculateFalloff(t, falloffStrength) {
517
- // t is 0 at center, 1 at edge
518
- // falloffStrength: 0 = hard edge, 1 = very smooth
519
- if (t >= 1) {
520
- return 0;
521
- }
522
- if (falloffStrength <= 0) {
523
- return 1;
524
- }
525
- const smoothT = t * t * (3 - 2 * t); // Smoothstep
526
- const power = 1 + falloffStrength * 3;
527
- return Math.pow(1 - smoothT, power);
528
- }
529
- // ─── Procedural Generation ─────────────────────────────
530
- generatePerlinTerrain(scale = 0.01, octaves = 6, persistence = 0.5) {
531
- const res = this.data.config.heightmapResolution;
532
- for (let z = 0; z < res; z++) {
533
- for (let x = 0; x < res; x++) {
534
- const height = this.perlinNoise2D(x * scale, z * scale, octaves, persistence);
535
- this.data.heightmap[z * res + x] = (height + 1) * 0.5; // Normalize to 0-1
536
- }
537
- }
538
- this.data.metadata.modifiedAt = Date.now();
539
- }
540
- generateDiamondSquare(roughness = 0.5) {
541
- const size = this.data.config.heightmapResolution;
542
- // Initialize corners
543
- this.data.heightmap[0] = Math.random();
544
- this.data.heightmap[size - 1] = Math.random();
545
- this.data.heightmap[(size - 1) * size] = Math.random();
546
- this.data.heightmap[(size - 1) * size + size - 1] = Math.random();
547
- let stepSize = size - 1;
548
- let scale = roughness;
549
- while (stepSize > 1) {
550
- const halfStep = stepSize / 2;
551
- // Diamond step
552
- for (let z = halfStep; z < size - 1; z += stepSize) {
553
- for (let x = halfStep; x < size - 1; x += stepSize) {
554
- const avg = (this.data.heightmap[(z - halfStep) * size + (x - halfStep)] +
555
- this.data.heightmap[(z - halfStep) * size + (x + halfStep)] +
556
- this.data.heightmap[(z + halfStep) * size + (x - halfStep)] +
557
- this.data.heightmap[(z + halfStep) * size + (x + halfStep)]) /
558
- 4;
559
- this.data.heightmap[z * size + x] = avg + (Math.random() - 0.5) * scale;
560
- }
561
- }
562
- // Square step
563
- for (let z = 0; z < size; z += halfStep) {
564
- for (let x = (z + halfStep) % stepSize; x < size; x += stepSize) {
565
- let sum = 0;
566
- let count = 0;
567
- if (z - halfStep >= 0) {
568
- sum += this.data.heightmap[(z - halfStep) * size + x];
569
- count++;
570
- }
571
- if (z + halfStep < size) {
572
- sum += this.data.heightmap[(z + halfStep) * size + x];
573
- count++;
574
- }
575
- if (x - halfStep >= 0) {
576
- sum += this.data.heightmap[z * size + (x - halfStep)];
577
- count++;
578
- }
579
- if (x + halfStep < size) {
580
- sum += this.data.heightmap[z * size + (x + halfStep)];
581
- count++;
582
- }
583
- this.data.heightmap[z * size + x] = sum / count + (Math.random() - 0.5) * scale;
584
- }
585
- }
586
- stepSize = halfStep;
587
- scale *= 0.5;
588
- }
589
- // Normalize
590
- let min = Infinity;
591
- let max = -Infinity;
592
- for (let i = 0; i < this.data.heightmap.length; i++) {
593
- min = Math.min(min, this.data.heightmap[i]);
594
- max = Math.max(max, this.data.heightmap[i]);
595
- }
596
- const range = max - min;
597
- if (range > 0) {
598
- for (let i = 0; i < this.data.heightmap.length; i++) {
599
- this.data.heightmap[i] = (this.data.heightmap[i] - min) / range;
600
- }
601
- }
602
- this.data.metadata.modifiedAt = Date.now();
603
- }
604
- applyHydraulicErosion(iterations = 50000) {
605
- const res = this.data.config.heightmapResolution;
606
- const { maxHeight: _maxHeight } = this.data.config;
607
- // Erosion parameters
608
- const inertia = 0.05;
609
- const sedimentCapacityFactor = 4;
610
- const minSedimentCapacity = 0.01;
611
- const erodeSpeed = 0.3;
612
- const depositSpeed = 0.3;
613
- const evaporateSpeed = 0.01;
614
- const gravity = 4;
615
- const maxDropletLifetime = 30;
616
- const initialWaterVolume = 1;
617
- const initialSpeed = 1;
618
- for (let i = 0; i < iterations; i++) {
619
- // Start at random position
620
- let posX = Math.random() * (res - 1);
621
- let posZ = Math.random() * (res - 1);
622
- let dirX = 0;
623
- let dirZ = 0;
624
- let speed = initialSpeed;
625
- let water = initialWaterVolume;
626
- let sediment = 0;
627
- for (let lifetime = 0; lifetime < maxDropletLifetime; lifetime++) {
628
- const cellX = Math.floor(posX);
629
- const cellZ = Math.floor(posZ);
630
- const cellOffsetX = posX - cellX;
631
- const cellOffsetZ = posZ - cellZ;
632
- // Calculate gradient
633
- const heightNW = this.data.heightmap[cellZ * res + cellX];
634
- const heightNE = cellX < res - 1 ? this.data.heightmap[cellZ * res + cellX + 1] : heightNW;
635
- const heightSW = cellZ < res - 1 ? this.data.heightmap[(cellZ + 1) * res + cellX] : heightNW;
636
- const heightSE = cellX < res - 1 && cellZ < res - 1
637
- ? this.data.heightmap[(cellZ + 1) * res + cellX + 1]
638
- : heightNW;
639
- const gradientX = (heightNE - heightNW) * (1 - cellOffsetZ) + (heightSE - heightSW) * cellOffsetZ;
640
- const gradientZ = (heightSW - heightNW) * (1 - cellOffsetX) + (heightSE - heightNE) * cellOffsetX;
641
- // Update direction with inertia
642
- dirX = dirX * inertia - gradientX * (1 - inertia);
643
- dirZ = dirZ * inertia - gradientZ * (1 - inertia);
644
- // Normalize direction
645
- const len = Math.sqrt(dirX * dirX + dirZ * dirZ);
646
- if (len > 0) {
647
- dirX /= len;
648
- dirZ /= len;
649
- }
650
- // Move
651
- posX += dirX;
652
- posZ += dirZ;
653
- // Check bounds
654
- if (posX < 0 || posX >= res - 1 || posZ < 0 || posZ >= res - 1 || len === 0) {
655
- break;
656
- }
657
- // Calculate height difference
658
- const newHeight = heightNW * (1 - cellOffsetX) * (1 - cellOffsetZ) +
659
- heightNE * cellOffsetX * (1 - cellOffsetZ) +
660
- heightSW * (1 - cellOffsetX) * cellOffsetZ +
661
- heightSE * cellOffsetX * cellOffsetZ;
662
- const oldHeight = this.data.heightmap[cellZ * res + cellX] * (1 - cellOffsetX) * (1 - cellOffsetZ) +
663
- (cellX < res - 1
664
- ? this.data.heightmap[cellZ * res + cellX + 1]
665
- : this.data.heightmap[cellZ * res + cellX]) *
666
- cellOffsetX *
667
- (1 - cellOffsetZ) +
668
- (cellZ < res - 1
669
- ? this.data.heightmap[(cellZ + 1) * res + cellX]
670
- : this.data.heightmap[cellZ * res + cellX]) *
671
- (1 - cellOffsetX) *
672
- cellOffsetZ +
673
- (cellX < res - 1 && cellZ < res - 1
674
- ? this.data.heightmap[(cellZ + 1) * res + cellX + 1]
675
- : this.data.heightmap[cellZ * res + cellX]) *
676
- cellOffsetX *
677
- cellOffsetZ;
678
- const heightDiff = newHeight - oldHeight;
679
- // Calculate sediment capacity
680
- const sedimentCapacity = Math.max(-heightDiff * speed * water * sedimentCapacityFactor, minSedimentCapacity);
681
- // Deposit or erode
682
- if (sediment > sedimentCapacity || heightDiff > 0) {
683
- // Deposit
684
- const depositAmount = heightDiff > 0
685
- ? Math.min(heightDiff, sediment)
686
- : (sediment - sedimentCapacity) * depositSpeed;
687
- sediment -= depositAmount;
688
- this.data.heightmap[cellZ * res + cellX] +=
689
- depositAmount * (1 - cellOffsetX) * (1 - cellOffsetZ);
690
- if (cellX < res - 1) {
691
- this.data.heightmap[cellZ * res + cellX + 1] +=
692
- depositAmount * cellOffsetX * (1 - cellOffsetZ);
693
- }
694
- if (cellZ < res - 1) {
695
- this.data.heightmap[(cellZ + 1) * res + cellX] +=
696
- depositAmount * (1 - cellOffsetX) * cellOffsetZ;
697
- }
698
- if (cellX < res - 1 && cellZ < res - 1) {
699
- this.data.heightmap[(cellZ + 1) * res + cellX + 1] +=
700
- depositAmount * cellOffsetX * cellOffsetZ;
701
- }
702
- }
703
- else {
704
- // Erode
705
- const erodeAmount = Math.min((sedimentCapacity - sediment) * erodeSpeed, -heightDiff);
706
- this.data.heightmap[cellZ * res + cellX] -=
707
- erodeAmount * (1 - cellOffsetX) * (1 - cellOffsetZ);
708
- if (cellX < res - 1) {
709
- this.data.heightmap[cellZ * res + cellX + 1] -=
710
- erodeAmount * cellOffsetX * (1 - cellOffsetZ);
711
- }
712
- if (cellZ < res - 1) {
713
- this.data.heightmap[(cellZ + 1) * res + cellX] -=
714
- erodeAmount * (1 - cellOffsetX) * cellOffsetZ;
715
- }
716
- if (cellX < res - 1 && cellZ < res - 1) {
717
- this.data.heightmap[(cellZ + 1) * res + cellX + 1] -=
718
- erodeAmount * cellOffsetX * cellOffsetZ;
719
- }
720
- sediment += erodeAmount;
721
- }
722
- // Update speed and water
723
- speed = Math.sqrt(Math.max(0, speed * speed + heightDiff * gravity));
724
- water *= 1 - evaporateSpeed;
725
- }
726
- }
727
- // Clamp heights
728
- for (let i = 0; i < this.data.heightmap.length; i++) {
729
- this.data.heightmap[i] = Math.max(0, Math.min(1, this.data.heightmap[i]));
730
- }
731
- this.data.metadata.modifiedAt = Date.now();
732
- }
733
- // ─── Perlin Noise ──────────────────────────────────────
734
- perlinNoise2D(x, y, octaves = 6, persistence = 0.5) {
735
- let total = 0;
736
- let frequency = 1;
737
- let amplitude = 1;
738
- let maxValue = 0;
739
- for (let i = 0; i < octaves; i++) {
740
- total += this.noise2D(x * frequency, y * frequency) * amplitude;
741
- maxValue += amplitude;
742
- amplitude *= persistence;
743
- frequency *= 2;
744
- }
745
- return total / maxValue;
746
- }
747
- noise2D(x, y) {
748
- // Simple hash-based noise
749
- const X = Math.floor(x) & 255;
750
- const Y = Math.floor(y) & 255;
751
- const xf = x - Math.floor(x);
752
- const yf = y - Math.floor(y);
753
- const topRight = this.dot2D(X + 1, Y, xf - 1, yf);
754
- const topLeft = this.dot2D(X, Y, xf, yf);
755
- const bottomRight = this.dot2D(X + 1, Y + 1, xf - 1, yf - 1);
756
- const bottomLeft = this.dot2D(X, Y + 1, xf, yf - 1);
757
- const u = this.fade(xf);
758
- const v = this.fade(yf);
759
- return this.lerp(this.lerp(topLeft, topRight, u), this.lerp(bottomLeft, bottomRight, u), v);
760
- }
761
- dot2D(ix, iy, x, y) {
762
- // Pseudo-random gradient
763
- const random = this.hash(ix, iy);
764
- const angle = random * Math.PI * 2;
765
- return x * Math.cos(angle) + y * Math.sin(angle);
766
- }
767
- hash(x, y) {
768
- const n = x + y * 57;
769
- const nn = (n << 13) ^ n;
770
- return ((nn * (nn * nn * 15731 + 789221) + 1376312589) & 0x7fffffff) / 2147483648.0;
771
- }
772
- fade(t) {
773
- return t * t * t * (t * (t * 6 - 15) + 10);
774
- }
775
- lerp(a, b, t) {
776
- return a + t * (b - a);
777
- }
778
- // ─── Foliage ───────────────────────────────────────────
779
- addDetailPrototype(prototype) {
780
- this.data.detailPrototypes.push(prototype);
781
- // Create corresponding density map
782
- const res = this.data.config.detailResolution;
783
- this.data.detailMaps.push(new Uint8Array(res * res));
784
- this.data.metadata.modifiedAt = Date.now();
785
- }
786
- paintDetail(worldX, worldZ, prototypeIndex, radius, density) {
787
- if (prototypeIndex >= this.data.detailMaps.length) {
788
- return;
789
- }
790
- const { width, detailResolution: res } = this.data.config;
791
- const densityMap = this.data.detailMaps[prototypeIndex];
792
- const gridX = ((worldX + width / 2) / width) * (res - 1);
793
- const gridZ = ((worldZ + width / 2) / width) * (res - 1);
794
- const gridRadius = (radius / width) * res;
795
- const minX = Math.max(0, Math.floor(gridX - gridRadius));
796
- const maxX = Math.min(res - 1, Math.ceil(gridX + gridRadius));
797
- const minZ = Math.max(0, Math.floor(gridZ - gridRadius));
798
- const maxZ = Math.min(res - 1, Math.ceil(gridZ + gridRadius));
799
- for (let z = minZ; z <= maxZ; z++) {
800
- for (let x = minX; x <= maxX; x++) {
801
- const dx = x - gridX;
802
- const dz = z - gridZ;
803
- const dist = Math.sqrt(dx * dx + dz * dz);
804
- if (dist <= gridRadius) {
805
- const falloff = 1 - dist / gridRadius;
806
- const idx = z * res + x;
807
- const current = densityMap[idx];
808
- densityMap[idx] = Math.min(255, current + density * falloff * 255);
809
- }
810
- }
811
- }
812
- this.data.metadata.modifiedAt = Date.now();
813
- }
814
- scatterFoliage(prototypeIndex, minSlope = 0, maxSlope = 45, minHeight = 0, maxHeight = 1) {
815
- if (prototypeIndex >= this.data.detailPrototypes.length) {
816
- return;
817
- }
818
- const { width, depth, heightmapResolution: _hmRes, detailResolution: res } = this.data.config;
819
- const densityMap = this.data.detailMaps[prototypeIndex];
820
- const prototype = this.data.detailPrototypes[prototypeIndex];
821
- for (let z = 0; z < res; z++) {
822
- for (let x = 0; x < res; x++) {
823
- const worldX = (x / (res - 1)) * width - width / 2;
824
- const worldZ = (z / (res - 1)) * depth - depth / 2;
825
- // Get terrain properties at this point
826
- const height = this.getHeightAtWorld(worldX, worldZ) / this.data.config.maxHeight;
827
- const normal = this.getNormalAtWorld(worldX, worldZ);
828
- const slope = Math.acos(normal.y) * (180 / Math.PI);
829
- // Check constraints
830
- const isValidHeight = height >= minHeight && height <= maxHeight;
831
- const isValidSlope = slope >= minSlope && slope <= maxSlope;
832
- if (isValidHeight && isValidSlope) {
833
- // Apply noise-based density
834
- const noise = (this.perlinNoise2D(x * 0.1, z * 0.1, 2) + 1) * 0.5;
835
- const baseDensity = prototype.density * noise;
836
- densityMap[z * res + x] = Math.min(255, densityMap[z * res + x] + baseDensity * 255);
837
- }
838
- }
839
- }
840
- this.data.metadata.modifiedAt = Date.now();
841
- }
842
- // ─── Trees ─────────────────────────────────────────────
843
- addTreePrototype(prototype) {
844
- this.data.treePrototypes.push(prototype);
845
- this.data.metadata.modifiedAt = Date.now();
846
- }
847
- addTree(worldX, worldZ, prototypeId, scale, rotation) {
848
- const prototype = this.data.treePrototypes.find((p) => p.id === prototypeId);
849
- if (!prototype) {
850
- return null;
851
- }
852
- const height = this.getHeightAtWorld(worldX, worldZ);
853
- const actualScale = scale ?? prototype.minScale + Math.random() * (prototype.maxScale - prototype.minScale);
854
- const actualRotation = rotation ?? (prototype.randomRotation ? Math.random() * Math.PI * 2 : 0);
855
- const instance = {
856
- position: { x: worldX, y: height, z: worldZ },
857
- rotation: actualRotation,
858
- scale: { x: actualScale, y: actualScale, z: actualScale },
859
- prototypeId,
860
- color: { r: 1, g: 1, b: 1, a: 1 },
861
- lightmapColor: { r: 1, g: 1, b: 1, a: 1 },
862
- };
863
- this.data.trees.push(instance);
864
- this.data.metadata.modifiedAt = Date.now();
865
- return instance;
866
- }
867
- scatterTrees(prototypeId, density, minSlope = 0, maxSlope = 30, minHeight = 0, maxHeight = 1, minSpacing = 5) {
868
- const prototype = this.data.treePrototypes.find((p) => p.id === prototypeId);
869
- if (!prototype) {
870
- return 0;
871
- }
872
- const { width, depth } = this.data.config;
873
- let treesAdded = 0;
874
- // Use Poisson disk sampling for natural distribution
875
- const cellSize = minSpacing / Math.SQRT2;
876
- const gridWidth = Math.ceil(width / cellSize);
877
- const gridDepth = Math.ceil(depth / cellSize);
878
- const grid = [];
879
- for (let i = 0; i < gridWidth; i++) {
880
- grid[i] = [];
881
- for (let j = 0; j < gridDepth; j++) {
882
- grid[i][j] = null;
883
- }
884
- }
885
- const numAttempts = Math.floor(width * depth * density);
886
- const activeList = [];
887
- // Start with a random point
888
- const startX = Math.random() * width - width / 2;
889
- const startZ = Math.random() * depth - depth / 2;
890
- const startHeight = this.getHeightAtWorld(startX, startZ);
891
- activeList.push({ x: startX, y: startHeight, z: startZ });
892
- for (let attempt = 0; attempt < numAttempts && activeList.length > 0; attempt++) {
893
- const idx = Math.floor(Math.random() * activeList.length);
894
- const point = activeList[idx];
895
- let found = false;
896
- for (let k = 0; k < 30; k++) {
897
- const angle = Math.random() * Math.PI * 2;
898
- const r = minSpacing + Math.random() * minSpacing;
899
- const newX = point.x + Math.cos(angle) * r;
900
- const newZ = point.z + Math.sin(angle) * r;
901
- // Check bounds
902
- if (newX < -width / 2 || newX > width / 2 || newZ < -depth / 2 || newZ > depth / 2) {
903
- continue;
904
- }
905
- // Check terrain constraints
906
- const newHeight = this.getHeightAtWorld(newX, newZ) / this.data.config.maxHeight;
907
- const normal = this.getNormalAtWorld(newX, newZ);
908
- const slope = Math.acos(normal.y) * (180 / Math.PI);
909
- if (newHeight < minHeight ||
910
- newHeight > maxHeight ||
911
- slope < minSlope ||
912
- slope > maxSlope) {
913
- continue;
914
- }
915
- // Check grid for nearby points
916
- const gridX = Math.floor((newX + width / 2) / cellSize);
917
- const gridZ = Math.floor((newZ + depth / 2) / cellSize);
918
- let tooClose = false;
919
- for (let di = -2; di <= 2 && !tooClose; di++) {
920
- for (let dj = -2; dj <= 2 && !tooClose; dj++) {
921
- const ni = gridX + di;
922
- const nj = gridZ + dj;
923
- if (ni >= 0 && ni < gridWidth && nj >= 0 && nj < gridDepth && grid[ni][nj]) {
924
- const neighbor = grid[ni][nj];
925
- const dx = neighbor.x - newX;
926
- const dz = neighbor.z - newZ;
927
- if (dx * dx + dz * dz < minSpacing * minSpacing) {
928
- tooClose = true;
929
- }
930
- }
931
- }
932
- }
933
- if (!tooClose) {
934
- const newPoint = { x: newX, y: this.getHeightAtWorld(newX, newZ), z: newZ };
935
- grid[gridX][gridZ] = newPoint;
936
- activeList.push(newPoint);
937
- this.addTree(newX, newZ, prototypeId);
938
- treesAdded++;
939
- found = true;
940
- break;
941
- }
942
- }
943
- if (!found) {
944
- activeList.splice(idx, 1);
945
- }
946
- }
947
- return treesAdded;
948
- }
949
- removeTreesInRadius(worldX, worldZ, radius) {
950
- const initialCount = this.data.trees.length;
951
- this.data.trees = this.data.trees.filter((tree) => {
952
- const dx = tree.position.x - worldX;
953
- const dz = tree.position.z - worldZ;
954
- return dx * dx + dz * dz > radius * radius;
955
- });
956
- this.data.metadata.modifiedAt = Date.now();
957
- return initialCount - this.data.trees.length;
958
- }
959
- // ─── Undo/Redo ─────────────────────────────────────────
960
- recordHeightChange(gridX, gridZ, oldValue, newValue) {
961
- const operation = {
962
- type: 'height',
963
- gridX,
964
- gridZ,
965
- oldValue,
966
- newValue,
967
- timestamp: Date.now(),
968
- };
969
- this.undoStack.push(operation);
970
- if (this.undoStack.length > this.maxUndoSteps) {
971
- this.undoStack.shift();
972
- }
973
- this.redoStack = [];
974
- }
975
- undo() {
976
- const operation = this.undoStack.pop();
977
- if (!operation) {
978
- return false;
979
- }
980
- if (operation.type === 'height') {
981
- const res = this.data.config.heightmapResolution;
982
- this.data.heightmap[operation.gridZ * res + operation.gridX] = operation.oldValue;
983
- }
984
- this.redoStack.push(operation);
985
- this.data.metadata.modifiedAt = Date.now();
986
- return true;
987
- }
988
- redo() {
989
- const operation = this.redoStack.pop();
990
- if (!operation) {
991
- return false;
992
- }
993
- if (operation.type === 'height') {
994
- const res = this.data.config.heightmapResolution;
995
- this.data.heightmap[operation.gridZ * res + operation.gridX] = operation.newValue;
996
- }
997
- this.undoStack.push(operation);
998
- this.data.metadata.modifiedAt = Date.now();
999
- return true;
1000
- }
1001
- // ─── Serialization ─────────────────────────────────────
1002
- getData() {
1003
- return this.data;
1004
- }
1005
- setData(data) {
1006
- this.data = data;
1007
- this.undoStack = [];
1008
- this.redoStack = [];
1009
- }
1010
- serialize() {
1011
- return JSON.stringify({
1012
- ...this.data,
1013
- heightmap: Array.from(this.data.heightmap),
1014
- splatmaps: this.data.splatmaps.map((s) => Array.from(s)),
1015
- holemap: Array.from(this.data.holemap),
1016
- detailMaps: this.data.detailMaps.map((d) => Array.from(d)),
76
+ constructor(config) {
77
+ this.undoStack = [];
78
+ this.redoStack = [];
79
+ this.maxUndoSteps = 50;
80
+ this.data = this.createEmptyTerrain(config);
81
+ }
82
+ createEmptyTerrain(configOverride) {
83
+ const config = { ...DEFAULT_TERRAIN_CONFIG, ...configOverride };
84
+ const hmRes = config.heightmapResolution;
85
+ const smRes = config.splatmapResolution;
86
+ config.detailResolution;
87
+ const chunks = config.chunksPerSide;
88
+ const heightmap = new Float32Array(hmRes * hmRes);
89
+ const splatmaps = [
90
+ new Uint8Array(smRes * smRes * 4),
91
+ new Uint8Array(smRes * smRes * 4)
92
+ ];
93
+ for (let i = 0; i < smRes * smRes; i++) {
94
+ splatmaps[0][i * 4] = 255;
95
+ }
96
+ const holemap = new Uint8Array(hmRes * hmRes);
97
+ holemap.fill(1);
98
+ const chunkList = [];
99
+ const chunkWidth = config.width / chunks;
100
+ const chunkDepth = config.depth / chunks;
101
+ for (let gz = 0; gz < chunks; gz++) {
102
+ for (let gx = 0; gx < chunks; gx++) {
103
+ chunkList.push({
104
+ id: `chunk_${gx}_${gz}`,
105
+ gridX: gx,
106
+ gridZ: gz,
107
+ boundsMin: {
108
+ x: gx * chunkWidth - config.width / 2,
109
+ y: 0,
110
+ z: gz * chunkDepth - config.depth / 2
111
+ },
112
+ boundsMax: {
113
+ x: (gx + 1) * chunkWidth - config.width / 2,
114
+ y: config.maxHeight,
115
+ z: (gz + 1) * chunkDepth - config.depth / 2
116
+ },
117
+ isLoaded: gx < 2 && gz < 2,
118
+ // Load center chunks
119
+ lodLevel: 0
1017
120
  });
121
+ }
1018
122
  }
1019
- static deserialize(json) {
1020
- const data = JSON.parse(json);
1021
- const terrain = new TerrainSystem(data.config);
1022
- terrain.data = {
1023
- ...data,
1024
- heightmap: new Float32Array(data.heightmap),
1025
- splatmaps: data.splatmaps.map((s) => new Uint8Array(s)),
1026
- holemap: new Uint8Array(data.holemap),
1027
- detailMaps: data.detailMaps.map((d) => new Uint8Array(d)),
1028
- };
1029
- return terrain;
1030
- }
1031
- // ─── Export Heightmap ──────────────────────────────────
1032
- exportHeightmapAsRAW() {
1033
- const res = this.data.config.heightmapResolution;
1034
- const buffer = new ArrayBuffer(res * res * 2); // 16-bit
1035
- const view = new Uint16Array(buffer);
1036
- for (let i = 0; i < this.data.heightmap.length; i++) {
1037
- view[i] = Math.round(this.data.heightmap[i] * 65535);
1038
- }
1039
- return buffer;
1040
- }
1041
- importHeightmapFromRAW(buffer, is16bit = true) {
1042
- const res = this.data.config.heightmapResolution;
1043
- if (is16bit) {
1044
- const view = new Uint16Array(buffer);
1045
- const expectedSize = res * res;
1046
- if (view.length !== expectedSize) {
1047
- throw new Error(`RAW size mismatch: expected ${expectedSize}, got ${view.length}`);
1048
- }
1049
- for (let i = 0; i < view.length; i++) {
1050
- this.data.heightmap[i] = view[i] / 65535;
123
+ return {
124
+ id: `terrain_${Date.now()}`,
125
+ name: "New Terrain",
126
+ config,
127
+ heightmap,
128
+ splatmaps,
129
+ holemap,
130
+ layers: [],
131
+ detailPrototypes: [],
132
+ detailMaps: [],
133
+ treePrototypes: [],
134
+ trees: [],
135
+ chunks: chunkList,
136
+ metadata: {
137
+ createdAt: Date.now(),
138
+ modifiedAt: Date.now(),
139
+ version: 1
140
+ }
141
+ };
142
+ }
143
+ // ─── Heightmap Operations ──────────────────────────────
144
+ /** Get height at grid coordinates (0 to resolution-1) */
145
+ getHeightAtGrid(gridX, gridZ) {
146
+ const res = this.data.config.heightmapResolution;
147
+ const x = Math.max(0, Math.min(res - 1, Math.floor(gridX)));
148
+ const z = Math.max(0, Math.min(res - 1, Math.floor(gridZ)));
149
+ return this.data.heightmap[z * res + x] * this.data.config.maxHeight;
150
+ }
151
+ /** Set height at grid coordinates */
152
+ setHeightAtGrid(gridX, gridZ, height, recordUndo = true) {
153
+ const res = this.data.config.heightmapResolution;
154
+ const maxH = this.data.config.maxHeight;
155
+ if (gridX < 0 || gridX >= res || gridZ < 0 || gridZ >= res) {
156
+ return;
157
+ }
158
+ const idx = gridZ * res + gridX;
159
+ const normalizedHeight = Math.max(0, Math.min(1, height / maxH));
160
+ if (recordUndo) {
161
+ this.recordHeightChange(gridX, gridZ, this.data.heightmap[idx], normalizedHeight);
162
+ }
163
+ this.data.heightmap[idx] = normalizedHeight;
164
+ this.data.metadata.modifiedAt = Date.now();
165
+ }
166
+ /** Get interpolated height at world coordinates */
167
+ getHeightAtWorld(worldX, worldZ) {
168
+ const { width, depth, heightmapResolution: res } = this.data.config;
169
+ const gx = (worldX + width / 2) / width * (res - 1);
170
+ const gz = (worldZ + depth / 2) / depth * (res - 1);
171
+ const ix = Math.floor(gx);
172
+ const iz = Math.floor(gz);
173
+ const fx = gx - ix;
174
+ const fz = gz - iz;
175
+ const h00 = this.getHeightAtGrid(ix, iz);
176
+ const h10 = this.getHeightAtGrid(ix + 1, iz);
177
+ const h01 = this.getHeightAtGrid(ix, iz + 1);
178
+ const h11 = this.getHeightAtGrid(ix + 1, iz + 1);
179
+ const h0 = h00 + (h10 - h00) * fx;
180
+ const h1 = h01 + (h11 - h01) * fx;
181
+ return h0 + (h1 - h0) * fz;
182
+ }
183
+ /** Convert world position to grid coordinates */
184
+ worldToGrid(worldX, worldZ) {
185
+ const { width, depth, heightmapResolution: res } = this.data.config;
186
+ return {
187
+ x: (worldX + width / 2) / width * (res - 1),
188
+ y: (worldZ + depth / 2) / depth * (res - 1)
189
+ };
190
+ }
191
+ /** Convert grid coordinates to world position */
192
+ gridToWorld(gridX, gridZ) {
193
+ const { width, depth, heightmapResolution: res } = this.data.config;
194
+ const worldX = gridX / (res - 1) * width - width / 2;
195
+ const worldZ = gridZ / (res - 1) * depth - depth / 2;
196
+ const worldY = this.getHeightAtGrid(gridX, gridZ);
197
+ return { x: worldX, y: worldY, z: worldZ };
198
+ }
199
+ /// Get terrain normal at world position
200
+ getNormalAtWorld(worldX, worldZ) {
201
+ const { width, depth, heightmapResolution: res } = this.data.config;
202
+ const cellWidth = width / (res - 1);
203
+ const cellDepth = depth / (res - 1);
204
+ const hL = this.getHeightAtWorld(worldX - cellWidth, worldZ);
205
+ const hR = this.getHeightAtWorld(worldX + cellWidth, worldZ);
206
+ const hD = this.getHeightAtWorld(worldX, worldZ - cellDepth);
207
+ const hU = this.getHeightAtWorld(worldX, worldZ + cellDepth);
208
+ const dx = hR - hL;
209
+ const dz = hU - hD;
210
+ const nx = -dx / (2 * cellWidth);
211
+ const ny = 1;
212
+ const nz = -dz / (2 * cellDepth);
213
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
214
+ return { x: nx / len, y: ny / len, z: nz / len };
215
+ }
216
+ // ─── Brush Operations ──────────────────────────────────
217
+ applyBrush(brush, worldX, worldZ) {
218
+ switch (brush.type) {
219
+ case "raise":
220
+ this.applyHeightBrush(worldX, worldZ, brush, 1);
221
+ break;
222
+ case "lower":
223
+ this.applyHeightBrush(worldX, worldZ, brush, -1);
224
+ break;
225
+ case "flatten":
226
+ this.applyFlattenBrush(worldX, worldZ, brush);
227
+ break;
228
+ case "smooth":
229
+ this.applySmoothBrush(worldX, worldZ, brush);
230
+ break;
231
+ case "noise":
232
+ this.applyNoiseBrush(worldX, worldZ, brush);
233
+ break;
234
+ case "erosion":
235
+ this.applyErosionBrush(worldX, worldZ, brush);
236
+ break;
237
+ case "paint":
238
+ this.applyPaintBrush(worldX, worldZ, brush);
239
+ break;
240
+ case "paintHoles":
241
+ this.applyHoleBrush(worldX, worldZ, brush);
242
+ break;
243
+ case "stampHeight":
244
+ this.applyStampBrush(worldX, worldZ, brush);
245
+ break;
246
+ }
247
+ }
248
+ applyHeightBrush(worldX, worldZ, brush, direction) {
249
+ const grid = this.worldToGrid(worldX, worldZ);
250
+ const { heightmapResolution: res, width, maxHeight } = this.data.config;
251
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
252
+ const delta = brush.strength * direction * maxHeight / 100;
253
+ const minX = Math.max(0, Math.floor(grid.x - gridRadius));
254
+ const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
255
+ const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
256
+ const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
257
+ for (let gz = minZ; gz <= maxZ; gz++) {
258
+ for (let gx = minX; gx <= maxX; gx++) {
259
+ const dx = gx - grid.x;
260
+ const dz = gz - grid.y;
261
+ const dist = Math.sqrt(dx * dx + dz * dz);
262
+ if (dist <= gridRadius) {
263
+ const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
264
+ const currentHeight = this.getHeightAtGrid(gx, gz);
265
+ const newHeight = currentHeight + delta * falloff;
266
+ this.setHeightAtGrid(gx, gz, newHeight);
267
+ }
268
+ }
269
+ }
270
+ }
271
+ applyFlattenBrush(worldX, worldZ, brush) {
272
+ const grid = this.worldToGrid(worldX, worldZ);
273
+ const { heightmapResolution: res, width } = this.data.config;
274
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
275
+ const targetHeight = brush.targetHeight ?? this.getHeightAtWorld(worldX, worldZ);
276
+ const minX = Math.max(0, Math.floor(grid.x - gridRadius));
277
+ const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
278
+ const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
279
+ const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
280
+ for (let gz = minZ; gz <= maxZ; gz++) {
281
+ for (let gx = minX; gx <= maxX; gx++) {
282
+ const dx = gx - grid.x;
283
+ const dz = gz - grid.y;
284
+ const dist = Math.sqrt(dx * dx + dz * dz);
285
+ if (dist <= gridRadius) {
286
+ const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
287
+ const currentHeight = this.getHeightAtGrid(gx, gz);
288
+ const newHeight = currentHeight + (targetHeight - currentHeight) * falloff * brush.strength;
289
+ this.setHeightAtGrid(gx, gz, newHeight);
290
+ }
291
+ }
292
+ }
293
+ }
294
+ applySmoothBrush(worldX, worldZ, brush) {
295
+ const grid = this.worldToGrid(worldX, worldZ);
296
+ const { heightmapResolution: res, width } = this.data.config;
297
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
298
+ const minX = Math.max(0, Math.floor(grid.x - gridRadius));
299
+ const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
300
+ const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
301
+ const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
302
+ const newHeights = [];
303
+ for (let gz = minZ; gz <= maxZ; gz++) {
304
+ for (let gx = minX; gx <= maxX; gx++) {
305
+ const dx = gx - grid.x;
306
+ const dz = gz - grid.y;
307
+ const dist = Math.sqrt(dx * dx + dz * dz);
308
+ if (dist <= gridRadius) {
309
+ let sum = 0;
310
+ let count = 0;
311
+ for (let nz = -1; nz <= 1; nz++) {
312
+ for (let nx = -1; nx <= 1; nx++) {
313
+ const ngx = gx + nx;
314
+ const ngz = gz + nz;
315
+ if (ngx >= 0 && ngx < res && ngz >= 0 && ngz < res) {
316
+ sum += this.getHeightAtGrid(ngx, ngz);
317
+ count++;
318
+ }
1051
319
  }
1052
- }
1053
- else {
1054
- const view = new Uint8Array(buffer);
1055
- const expectedSize = res * res;
1056
- if (view.length !== expectedSize) {
1057
- throw new Error(`RAW size mismatch: expected ${expectedSize}, got ${view.length}`);
320
+ }
321
+ const avgHeight = sum / count;
322
+ const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
323
+ const currentHeight = this.getHeightAtGrid(gx, gz);
324
+ const newHeight = currentHeight + (avgHeight - currentHeight) * falloff * brush.strength;
325
+ newHeights.push({ gx, gz, height: newHeight });
326
+ }
327
+ }
328
+ }
329
+ for (const { gx, gz, height } of newHeights) {
330
+ this.setHeightAtGrid(gx, gz, height);
331
+ }
332
+ }
333
+ applyNoiseBrush(worldX, worldZ, brush) {
334
+ const grid = this.worldToGrid(worldX, worldZ);
335
+ const { heightmapResolution: res, width, maxHeight } = this.data.config;
336
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
337
+ const noiseScale = brush.noiseScale ?? 0.1;
338
+ const octaves = brush.noiseOctaves ?? 4;
339
+ const minX = Math.max(0, Math.floor(grid.x - gridRadius));
340
+ const maxX = Math.min(res - 1, Math.ceil(grid.x + gridRadius));
341
+ const minZ = Math.max(0, Math.floor(grid.y - gridRadius));
342
+ const maxZ = Math.min(res - 1, Math.ceil(grid.y + gridRadius));
343
+ for (let gz = minZ; gz <= maxZ; gz++) {
344
+ for (let gx = minX; gx <= maxX; gx++) {
345
+ const dx = gx - grid.x;
346
+ const dz = gz - grid.y;
347
+ const dist = Math.sqrt(dx * dx + dz * dz);
348
+ if (dist <= gridRadius) {
349
+ const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
350
+ const noise = this.perlinNoise2D(gx * noiseScale, gz * noiseScale, octaves);
351
+ const delta = noise * brush.strength * maxHeight * 0.1 * falloff;
352
+ const currentHeight = this.getHeightAtGrid(gx, gz);
353
+ this.setHeightAtGrid(gx, gz, currentHeight + delta);
354
+ }
355
+ }
356
+ }
357
+ }
358
+ applyErosionBrush(worldX, worldZ, brush) {
359
+ const grid = this.worldToGrid(worldX, worldZ);
360
+ const { heightmapResolution: res, width } = this.data.config;
361
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
362
+ const minX = Math.max(1, Math.floor(grid.x - gridRadius));
363
+ const maxX = Math.min(res - 2, Math.ceil(grid.x + gridRadius));
364
+ const minZ = Math.max(1, Math.floor(grid.y - gridRadius));
365
+ const maxZ = Math.min(res - 2, Math.ceil(grid.y + gridRadius));
366
+ const newHeights = [];
367
+ const talusAngle = 0.5;
368
+ for (let gz = minZ; gz <= maxZ; gz++) {
369
+ for (let gx = minX; gx <= maxX; gx++) {
370
+ const dx = gx - grid.x;
371
+ const dz = gz - grid.y;
372
+ const dist = Math.sqrt(dx * dx + dz * dz);
373
+ if (dist <= gridRadius) {
374
+ const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
375
+ const h = this.getHeightAtGrid(gx, gz);
376
+ let totalDiff = 0;
377
+ const neighbors = [
378
+ this.getHeightAtGrid(gx - 1, gz),
379
+ this.getHeightAtGrid(gx + 1, gz),
380
+ this.getHeightAtGrid(gx, gz - 1),
381
+ this.getHeightAtGrid(gx, gz + 1)
382
+ ];
383
+ for (const nh of neighbors) {
384
+ const diff = h - nh;
385
+ if (diff > talusAngle) {
386
+ totalDiff += diff - talusAngle;
1058
387
  }
1059
- for (let i = 0; i < view.length; i++) {
1060
- this.data.heightmap[i] = view[i] / 255;
388
+ }
389
+ if (totalDiff > 0) {
390
+ const erosion = totalDiff * brush.strength * falloff * 0.25;
391
+ newHeights.push({ gx, gz, height: h - erosion });
392
+ }
393
+ }
394
+ }
395
+ }
396
+ for (const { gx, gz, height } of newHeights) {
397
+ this.setHeightAtGrid(gx, gz, height);
398
+ }
399
+ }
400
+ applyPaintBrush(worldX, worldZ, brush) {
401
+ const { splatmapResolution: res, width } = this.data.config;
402
+ const layerIndex = brush.layerIndex ?? 0;
403
+ if (layerIndex >= 8) {
404
+ return;
405
+ }
406
+ const splatmapIndex = Math.floor(layerIndex / 4);
407
+ const channelIndex = layerIndex % 4;
408
+ const smX = (worldX + width / 2) / width * (res - 1);
409
+ const smZ = (worldZ + width / 2) / width * (res - 1);
410
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
411
+ const minX = Math.max(0, Math.floor(smX - gridRadius));
412
+ const maxX = Math.min(res - 1, Math.ceil(smX + gridRadius));
413
+ const minZ = Math.max(0, Math.floor(smZ - gridRadius));
414
+ const maxZ = Math.min(res - 1, Math.ceil(smZ + gridRadius));
415
+ const splatmap = this.data.splatmaps[splatmapIndex];
416
+ for (let z = minZ; z <= maxZ; z++) {
417
+ for (let x = minX; x <= maxX; x++) {
418
+ const dx = x - smX;
419
+ const dz = z - smZ;
420
+ const dist = Math.sqrt(dx * dx + dz * dz);
421
+ if (dist <= gridRadius) {
422
+ const falloff = this.calculateFalloff(dist / gridRadius, brush.falloff);
423
+ const idx = (z * res + x) * 4;
424
+ const strength = brush.strength * falloff * 255;
425
+ const current = splatmap[idx + channelIndex];
426
+ const newValue = Math.min(255, current + strength);
427
+ splatmap[idx + channelIndex] = newValue;
428
+ this.normalizeSplatmapPixel(x, z);
429
+ }
430
+ }
431
+ }
432
+ this.data.metadata.modifiedAt = Date.now();
433
+ }
434
+ normalizeSplatmapPixel(x, z) {
435
+ const res = this.data.config.splatmapResolution;
436
+ let total = 0;
437
+ for (let s = 0; s < 2; s++) {
438
+ const idx = (z * res + x) * 4;
439
+ for (let c = 0; c < 4; c++) {
440
+ total += this.data.splatmaps[s][idx + c];
441
+ }
442
+ }
443
+ if (total > 0) {
444
+ const scale = 255 / total;
445
+ for (let s = 0; s < 2; s++) {
446
+ const idx = (z * res + x) * 4;
447
+ for (let c = 0; c < 4; c++) {
448
+ this.data.splatmaps[s][idx + c] = Math.round(this.data.splatmaps[s][idx + c] * scale);
449
+ }
450
+ }
451
+ }
452
+ }
453
+ applyHoleBrush(worldX, worldZ, brush) {
454
+ const { heightmapResolution: res, width } = this.data.config;
455
+ const gridCoords = this.worldToGrid(worldX, worldZ);
456
+ const gridRadius = brush.size / (width / (res - 1)) * 0.5;
457
+ const isAddHole = brush.strength > 0;
458
+ const minX = Math.max(0, Math.floor(gridCoords.x - gridRadius));
459
+ const maxX = Math.min(res - 1, Math.ceil(gridCoords.x + gridRadius));
460
+ const minZ = Math.max(0, Math.floor(gridCoords.y - gridRadius));
461
+ const maxZ = Math.min(res - 1, Math.ceil(gridCoords.y + gridRadius));
462
+ for (let gz = minZ; gz <= maxZ; gz++) {
463
+ for (let gx = minX; gx <= maxX; gx++) {
464
+ const dx = gx - gridCoords.x;
465
+ const dz = gz - gridCoords.y;
466
+ const dist = Math.sqrt(dx * dx + dz * dz);
467
+ if (dist <= gridRadius) {
468
+ this.data.holemap[gz * res + gx] = isAddHole ? 0 : 1;
469
+ }
470
+ }
471
+ }
472
+ this.data.metadata.modifiedAt = Date.now();
473
+ }
474
+ applyStampBrush(worldX, worldZ, brush) {
475
+ this.applyHeightBrush(worldX, worldZ, brush, 1);
476
+ }
477
+ calculateFalloff(t, falloffStrength) {
478
+ if (t >= 1) {
479
+ return 0;
480
+ }
481
+ if (falloffStrength <= 0) {
482
+ return 1;
483
+ }
484
+ const smoothT = t * t * (3 - 2 * t);
485
+ const power = 1 + falloffStrength * 3;
486
+ return Math.pow(1 - smoothT, power);
487
+ }
488
+ // ─── Procedural Generation ─────────────────────────────
489
+ generatePerlinTerrain(scale = 0.01, octaves = 6, persistence = 0.5) {
490
+ const res = this.data.config.heightmapResolution;
491
+ for (let z = 0; z < res; z++) {
492
+ for (let x = 0; x < res; x++) {
493
+ const height = this.perlinNoise2D(x * scale, z * scale, octaves, persistence);
494
+ this.data.heightmap[z * res + x] = (height + 1) * 0.5;
495
+ }
496
+ }
497
+ this.data.metadata.modifiedAt = Date.now();
498
+ }
499
+ generateDiamondSquare(roughness = 0.5) {
500
+ const size = this.data.config.heightmapResolution;
501
+ this.data.heightmap[0] = Math.random();
502
+ this.data.heightmap[size - 1] = Math.random();
503
+ this.data.heightmap[(size - 1) * size] = Math.random();
504
+ this.data.heightmap[(size - 1) * size + size - 1] = Math.random();
505
+ let stepSize = size - 1;
506
+ let scale = roughness;
507
+ while (stepSize > 1) {
508
+ const halfStep = stepSize / 2;
509
+ for (let z = halfStep; z < size - 1; z += stepSize) {
510
+ for (let x = halfStep; x < size - 1; x += stepSize) {
511
+ const avg = (this.data.heightmap[(z - halfStep) * size + (x - halfStep)] + this.data.heightmap[(z - halfStep) * size + (x + halfStep)] + this.data.heightmap[(z + halfStep) * size + (x - halfStep)] + this.data.heightmap[(z + halfStep) * size + (x + halfStep)]) / 4;
512
+ this.data.heightmap[z * size + x] = avg + (Math.random() - 0.5) * scale;
513
+ }
514
+ }
515
+ for (let z = 0; z < size; z += halfStep) {
516
+ for (let x = (z + halfStep) % stepSize; x < size; x += stepSize) {
517
+ let sum = 0;
518
+ let count = 0;
519
+ if (z - halfStep >= 0) {
520
+ sum += this.data.heightmap[(z - halfStep) * size + x];
521
+ count++;
522
+ }
523
+ if (z + halfStep < size) {
524
+ sum += this.data.heightmap[(z + halfStep) * size + x];
525
+ count++;
526
+ }
527
+ if (x - halfStep >= 0) {
528
+ sum += this.data.heightmap[z * size + (x - halfStep)];
529
+ count++;
530
+ }
531
+ if (x + halfStep < size) {
532
+ sum += this.data.heightmap[z * size + (x + halfStep)];
533
+ count++;
534
+ }
535
+ this.data.heightmap[z * size + x] = sum / count + (Math.random() - 0.5) * scale;
536
+ }
537
+ }
538
+ stepSize = halfStep;
539
+ scale *= 0.5;
540
+ }
541
+ let min = Infinity;
542
+ let max = -Infinity;
543
+ for (let i = 0; i < this.data.heightmap.length; i++) {
544
+ min = Math.min(min, this.data.heightmap[i]);
545
+ max = Math.max(max, this.data.heightmap[i]);
546
+ }
547
+ const range = max - min;
548
+ if (range > 0) {
549
+ for (let i = 0; i < this.data.heightmap.length; i++) {
550
+ this.data.heightmap[i] = (this.data.heightmap[i] - min) / range;
551
+ }
552
+ }
553
+ this.data.metadata.modifiedAt = Date.now();
554
+ }
555
+ applyHydraulicErosion(iterations = 5e4) {
556
+ const res = this.data.config.heightmapResolution;
557
+ const { maxHeight: _maxHeight } = this.data.config;
558
+ const inertia = 0.05;
559
+ const sedimentCapacityFactor = 4;
560
+ const minSedimentCapacity = 0.01;
561
+ const erodeSpeed = 0.3;
562
+ const depositSpeed = 0.3;
563
+ const evaporateSpeed = 0.01;
564
+ const gravity = 4;
565
+ const maxDropletLifetime = 30;
566
+ const initialWaterVolume = 1;
567
+ const initialSpeed = 1;
568
+ for (let i = 0; i < iterations; i++) {
569
+ let posX = Math.random() * (res - 1);
570
+ let posZ = Math.random() * (res - 1);
571
+ let dirX = 0;
572
+ let dirZ = 0;
573
+ let speed = initialSpeed;
574
+ let water = initialWaterVolume;
575
+ let sediment = 0;
576
+ for (let lifetime = 0; lifetime < maxDropletLifetime; lifetime++) {
577
+ const cellX = Math.floor(posX);
578
+ const cellZ = Math.floor(posZ);
579
+ const cellOffsetX = posX - cellX;
580
+ const cellOffsetZ = posZ - cellZ;
581
+ const heightNW = this.data.heightmap[cellZ * res + cellX];
582
+ const heightNE = cellX < res - 1 ? this.data.heightmap[cellZ * res + cellX + 1] : heightNW;
583
+ const heightSW = cellZ < res - 1 ? this.data.heightmap[(cellZ + 1) * res + cellX] : heightNW;
584
+ const heightSE = cellX < res - 1 && cellZ < res - 1 ? this.data.heightmap[(cellZ + 1) * res + cellX + 1] : heightNW;
585
+ const gradientX = (heightNE - heightNW) * (1 - cellOffsetZ) + (heightSE - heightSW) * cellOffsetZ;
586
+ const gradientZ = (heightSW - heightNW) * (1 - cellOffsetX) + (heightSE - heightNE) * cellOffsetX;
587
+ dirX = dirX * inertia - gradientX * (1 - inertia);
588
+ dirZ = dirZ * inertia - gradientZ * (1 - inertia);
589
+ const len = Math.sqrt(dirX * dirX + dirZ * dirZ);
590
+ if (len > 0) {
591
+ dirX /= len;
592
+ dirZ /= len;
593
+ }
594
+ posX += dirX;
595
+ posZ += dirZ;
596
+ if (posX < 0 || posX >= res - 1 || posZ < 0 || posZ >= res - 1 || len === 0) {
597
+ break;
598
+ }
599
+ const newHeight = heightNW * (1 - cellOffsetX) * (1 - cellOffsetZ) + heightNE * cellOffsetX * (1 - cellOffsetZ) + heightSW * (1 - cellOffsetX) * cellOffsetZ + heightSE * cellOffsetX * cellOffsetZ;
600
+ const oldHeight = this.data.heightmap[cellZ * res + cellX] * (1 - cellOffsetX) * (1 - cellOffsetZ) + (cellX < res - 1 ? this.data.heightmap[cellZ * res + cellX + 1] : this.data.heightmap[cellZ * res + cellX]) * cellOffsetX * (1 - cellOffsetZ) + (cellZ < res - 1 ? this.data.heightmap[(cellZ + 1) * res + cellX] : this.data.heightmap[cellZ * res + cellX]) * (1 - cellOffsetX) * cellOffsetZ + (cellX < res - 1 && cellZ < res - 1 ? this.data.heightmap[(cellZ + 1) * res + cellX + 1] : this.data.heightmap[cellZ * res + cellX]) * cellOffsetX * cellOffsetZ;
601
+ const heightDiff = newHeight - oldHeight;
602
+ const sedimentCapacity = Math.max(
603
+ -heightDiff * speed * water * sedimentCapacityFactor,
604
+ minSedimentCapacity
605
+ );
606
+ if (sediment > sedimentCapacity || heightDiff > 0) {
607
+ const depositAmount = heightDiff > 0 ? Math.min(heightDiff, sediment) : (sediment - sedimentCapacity) * depositSpeed;
608
+ sediment -= depositAmount;
609
+ this.data.heightmap[cellZ * res + cellX] += depositAmount * (1 - cellOffsetX) * (1 - cellOffsetZ);
610
+ if (cellX < res - 1) {
611
+ this.data.heightmap[cellZ * res + cellX + 1] += depositAmount * cellOffsetX * (1 - cellOffsetZ);
612
+ }
613
+ if (cellZ < res - 1) {
614
+ this.data.heightmap[(cellZ + 1) * res + cellX] += depositAmount * (1 - cellOffsetX) * cellOffsetZ;
615
+ }
616
+ if (cellX < res - 1 && cellZ < res - 1) {
617
+ this.data.heightmap[(cellZ + 1) * res + cellX + 1] += depositAmount * cellOffsetX * cellOffsetZ;
618
+ }
619
+ } else {
620
+ const erodeAmount = Math.min((sedimentCapacity - sediment) * erodeSpeed, -heightDiff);
621
+ this.data.heightmap[cellZ * res + cellX] -= erodeAmount * (1 - cellOffsetX) * (1 - cellOffsetZ);
622
+ if (cellX < res - 1) {
623
+ this.data.heightmap[cellZ * res + cellX + 1] -= erodeAmount * cellOffsetX * (1 - cellOffsetZ);
624
+ }
625
+ if (cellZ < res - 1) {
626
+ this.data.heightmap[(cellZ + 1) * res + cellX] -= erodeAmount * (1 - cellOffsetX) * cellOffsetZ;
627
+ }
628
+ if (cellX < res - 1 && cellZ < res - 1) {
629
+ this.data.heightmap[(cellZ + 1) * res + cellX + 1] -= erodeAmount * cellOffsetX * cellOffsetZ;
630
+ }
631
+ sediment += erodeAmount;
632
+ }
633
+ speed = Math.sqrt(Math.max(0, speed * speed + heightDiff * gravity));
634
+ water *= 1 - evaporateSpeed;
635
+ }
636
+ }
637
+ for (let i = 0; i < this.data.heightmap.length; i++) {
638
+ this.data.heightmap[i] = Math.max(0, Math.min(1, this.data.heightmap[i]));
639
+ }
640
+ this.data.metadata.modifiedAt = Date.now();
641
+ }
642
+ // ─── Perlin Noise ──────────────────────────────────────
643
+ perlinNoise2D(x, y, octaves = 6, persistence = 0.5) {
644
+ let total = 0;
645
+ let frequency = 1;
646
+ let amplitude = 1;
647
+ let maxValue = 0;
648
+ for (let i = 0; i < octaves; i++) {
649
+ total += this.noise2D(x * frequency, y * frequency) * amplitude;
650
+ maxValue += amplitude;
651
+ amplitude *= persistence;
652
+ frequency *= 2;
653
+ }
654
+ return total / maxValue;
655
+ }
656
+ noise2D(x, y) {
657
+ const X = Math.floor(x) & 255;
658
+ const Y = Math.floor(y) & 255;
659
+ const xf = x - Math.floor(x);
660
+ const yf = y - Math.floor(y);
661
+ const topRight = this.dot2D(X + 1, Y, xf - 1, yf);
662
+ const topLeft = this.dot2D(X, Y, xf, yf);
663
+ const bottomRight = this.dot2D(X + 1, Y + 1, xf - 1, yf - 1);
664
+ const bottomLeft = this.dot2D(X, Y + 1, xf, yf - 1);
665
+ const u = this.fade(xf);
666
+ const v = this.fade(yf);
667
+ return this.lerp(this.lerp(topLeft, topRight, u), this.lerp(bottomLeft, bottomRight, u), v);
668
+ }
669
+ dot2D(ix, iy, x, y) {
670
+ const random = this.hash(ix, iy);
671
+ const angle = random * Math.PI * 2;
672
+ return x * Math.cos(angle) + y * Math.sin(angle);
673
+ }
674
+ hash(x, y) {
675
+ const n = x + y * 57;
676
+ const nn = n << 13 ^ n;
677
+ return (nn * (nn * nn * 15731 + 789221) + 1376312589 & 2147483647) / 2147483648;
678
+ }
679
+ fade(t) {
680
+ return t * t * t * (t * (t * 6 - 15) + 10);
681
+ }
682
+ lerp(a, b, t) {
683
+ return a + t * (b - a);
684
+ }
685
+ // ─── Foliage ───────────────────────────────────────────
686
+ addDetailPrototype(prototype) {
687
+ this.data.detailPrototypes.push(prototype);
688
+ const res = this.data.config.detailResolution;
689
+ this.data.detailMaps.push(new Uint8Array(res * res));
690
+ this.data.metadata.modifiedAt = Date.now();
691
+ }
692
+ paintDetail(worldX, worldZ, prototypeIndex, radius, density) {
693
+ if (prototypeIndex >= this.data.detailMaps.length) {
694
+ return;
695
+ }
696
+ const { width, detailResolution: res } = this.data.config;
697
+ const densityMap = this.data.detailMaps[prototypeIndex];
698
+ const gridX = (worldX + width / 2) / width * (res - 1);
699
+ const gridZ = (worldZ + width / 2) / width * (res - 1);
700
+ const gridRadius = radius / width * res;
701
+ const minX = Math.max(0, Math.floor(gridX - gridRadius));
702
+ const maxX = Math.min(res - 1, Math.ceil(gridX + gridRadius));
703
+ const minZ = Math.max(0, Math.floor(gridZ - gridRadius));
704
+ const maxZ = Math.min(res - 1, Math.ceil(gridZ + gridRadius));
705
+ for (let z = minZ; z <= maxZ; z++) {
706
+ for (let x = minX; x <= maxX; x++) {
707
+ const dx = x - gridX;
708
+ const dz = z - gridZ;
709
+ const dist = Math.sqrt(dx * dx + dz * dz);
710
+ if (dist <= gridRadius) {
711
+ const falloff = 1 - dist / gridRadius;
712
+ const idx = z * res + x;
713
+ const current = densityMap[idx];
714
+ densityMap[idx] = Math.min(255, current + density * falloff * 255);
715
+ }
716
+ }
717
+ }
718
+ this.data.metadata.modifiedAt = Date.now();
719
+ }
720
+ scatterFoliage(prototypeIndex, minSlope = 0, maxSlope = 45, minHeight = 0, maxHeight = 1) {
721
+ if (prototypeIndex >= this.data.detailPrototypes.length) {
722
+ return;
723
+ }
724
+ const { width, depth, heightmapResolution: _hmRes, detailResolution: res } = this.data.config;
725
+ const densityMap = this.data.detailMaps[prototypeIndex];
726
+ const prototype = this.data.detailPrototypes[prototypeIndex];
727
+ for (let z = 0; z < res; z++) {
728
+ for (let x = 0; x < res; x++) {
729
+ const worldX = x / (res - 1) * width - width / 2;
730
+ const worldZ = z / (res - 1) * depth - depth / 2;
731
+ const height = this.getHeightAtWorld(worldX, worldZ) / this.data.config.maxHeight;
732
+ const normal = this.getNormalAtWorld(worldX, worldZ);
733
+ const slope = Math.acos(normal.y) * (180 / Math.PI);
734
+ const isValidHeight = height >= minHeight && height <= maxHeight;
735
+ const isValidSlope = slope >= minSlope && slope <= maxSlope;
736
+ if (isValidHeight && isValidSlope) {
737
+ const noise = (this.perlinNoise2D(x * 0.1, z * 0.1, 2) + 1) * 0.5;
738
+ const baseDensity = prototype.density * noise;
739
+ densityMap[z * res + x] = Math.min(255, densityMap[z * res + x] + baseDensity * 255);
740
+ }
741
+ }
742
+ }
743
+ this.data.metadata.modifiedAt = Date.now();
744
+ }
745
+ // ─── Trees ─────────────────────────────────────────────
746
+ addTreePrototype(prototype) {
747
+ this.data.treePrototypes.push(prototype);
748
+ this.data.metadata.modifiedAt = Date.now();
749
+ }
750
+ addTree(worldX, worldZ, prototypeId, scale, rotation) {
751
+ const prototype = this.data.treePrototypes.find((p) => p.id === prototypeId);
752
+ if (!prototype) {
753
+ return null;
754
+ }
755
+ const height = this.getHeightAtWorld(worldX, worldZ);
756
+ const actualScale = scale ?? prototype.minScale + Math.random() * (prototype.maxScale - prototype.minScale);
757
+ const actualRotation = rotation ?? (prototype.randomRotation ? Math.random() * Math.PI * 2 : 0);
758
+ const instance = {
759
+ position: { x: worldX, y: height, z: worldZ },
760
+ rotation: actualRotation,
761
+ scale: { x: actualScale, y: actualScale, z: actualScale },
762
+ prototypeId,
763
+ color: { r: 1, g: 1, b: 1, a: 1 },
764
+ lightmapColor: { r: 1, g: 1, b: 1, a: 1 }
765
+ };
766
+ this.data.trees.push(instance);
767
+ this.data.metadata.modifiedAt = Date.now();
768
+ return instance;
769
+ }
770
+ scatterTrees(prototypeId, density, minSlope = 0, maxSlope = 30, minHeight = 0, maxHeight = 1, minSpacing = 5) {
771
+ const prototype = this.data.treePrototypes.find((p) => p.id === prototypeId);
772
+ if (!prototype) {
773
+ return 0;
774
+ }
775
+ const { width, depth } = this.data.config;
776
+ let treesAdded = 0;
777
+ const cellSize = minSpacing / Math.SQRT2;
778
+ const gridWidth = Math.ceil(width / cellSize);
779
+ const gridDepth = Math.ceil(depth / cellSize);
780
+ const grid = [];
781
+ for (let i = 0; i < gridWidth; i++) {
782
+ grid[i] = [];
783
+ for (let j = 0; j < gridDepth; j++) {
784
+ grid[i][j] = null;
785
+ }
786
+ }
787
+ const numAttempts = Math.floor(width * depth * density);
788
+ const activeList = [];
789
+ const startX = Math.random() * width - width / 2;
790
+ const startZ = Math.random() * depth - depth / 2;
791
+ const startHeight = this.getHeightAtWorld(startX, startZ);
792
+ activeList.push({ x: startX, y: startHeight, z: startZ });
793
+ for (let attempt = 0; attempt < numAttempts && activeList.length > 0; attempt++) {
794
+ const idx = Math.floor(Math.random() * activeList.length);
795
+ const point = activeList[idx];
796
+ let found = false;
797
+ for (let k = 0; k < 30; k++) {
798
+ const angle = Math.random() * Math.PI * 2;
799
+ const r = minSpacing + Math.random() * minSpacing;
800
+ const newX = point.x + Math.cos(angle) * r;
801
+ const newZ = point.z + Math.sin(angle) * r;
802
+ if (newX < -width / 2 || newX > width / 2 || newZ < -depth / 2 || newZ > depth / 2) {
803
+ continue;
804
+ }
805
+ const newHeight = this.getHeightAtWorld(newX, newZ) / this.data.config.maxHeight;
806
+ const normal = this.getNormalAtWorld(newX, newZ);
807
+ const slope = Math.acos(normal.y) * (180 / Math.PI);
808
+ if (newHeight < minHeight || newHeight > maxHeight || slope < minSlope || slope > maxSlope) {
809
+ continue;
810
+ }
811
+ const gridX = Math.floor((newX + width / 2) / cellSize);
812
+ const gridZ = Math.floor((newZ + depth / 2) / cellSize);
813
+ let tooClose = false;
814
+ for (let di = -2; di <= 2 && !tooClose; di++) {
815
+ for (let dj = -2; dj <= 2 && !tooClose; dj++) {
816
+ const ni = gridX + di;
817
+ const nj = gridZ + dj;
818
+ if (ni >= 0 && ni < gridWidth && nj >= 0 && nj < gridDepth && grid[ni][nj]) {
819
+ const neighbor = grid[ni][nj];
820
+ const dx = neighbor.x - newX;
821
+ const dz = neighbor.z - newZ;
822
+ if (dx * dx + dz * dz < minSpacing * minSpacing) {
823
+ tooClose = true;
824
+ }
1061
825
  }
1062
- }
1063
- this.data.metadata.modifiedAt = Date.now();
1064
- }
1065
- exportSplatmapAsPNG(splatmapIndex) {
1066
- if (splatmapIndex >= this.data.splatmaps.length) {
1067
- return null;
1068
- }
1069
- const res = this.data.config.splatmapResolution;
1070
- const splatmap = this.data.splatmaps[splatmapIndex];
1071
- const imageData = new ImageData(res, res);
1072
- for (let i = 0; i < splatmap.length; i++) {
1073
- imageData.data[i] = splatmap[i];
1074
- }
1075
- return imageData;
1076
- }
826
+ }
827
+ }
828
+ if (!tooClose) {
829
+ const newPoint = { x: newX, y: this.getHeightAtWorld(newX, newZ), z: newZ };
830
+ grid[gridX][gridZ] = newPoint;
831
+ activeList.push(newPoint);
832
+ this.addTree(newX, newZ, prototypeId);
833
+ treesAdded++;
834
+ found = true;
835
+ break;
836
+ }
837
+ }
838
+ if (!found) {
839
+ activeList.splice(idx, 1);
840
+ }
841
+ }
842
+ return treesAdded;
843
+ }
844
+ removeTreesInRadius(worldX, worldZ, radius) {
845
+ const initialCount = this.data.trees.length;
846
+ this.data.trees = this.data.trees.filter((tree) => {
847
+ const dx = tree.position.x - worldX;
848
+ const dz = tree.position.z - worldZ;
849
+ return dx * dx + dz * dz > radius * radius;
850
+ });
851
+ this.data.metadata.modifiedAt = Date.now();
852
+ return initialCount - this.data.trees.length;
853
+ }
854
+ // ─── Undo/Redo ─────────────────────────────────────────
855
+ recordHeightChange(gridX, gridZ, oldValue, newValue) {
856
+ const operation = {
857
+ type: "height",
858
+ gridX,
859
+ gridZ,
860
+ oldValue,
861
+ newValue,
862
+ timestamp: Date.now()
863
+ };
864
+ this.undoStack.push(operation);
865
+ if (this.undoStack.length > this.maxUndoSteps) {
866
+ this.undoStack.shift();
867
+ }
868
+ this.redoStack = [];
869
+ }
870
+ undo() {
871
+ const operation = this.undoStack.pop();
872
+ if (!operation) {
873
+ return false;
874
+ }
875
+ if (operation.type === "height") {
876
+ const res = this.data.config.heightmapResolution;
877
+ this.data.heightmap[operation.gridZ * res + operation.gridX] = operation.oldValue;
878
+ }
879
+ this.redoStack.push(operation);
880
+ this.data.metadata.modifiedAt = Date.now();
881
+ return true;
882
+ }
883
+ redo() {
884
+ const operation = this.redoStack.pop();
885
+ if (!operation) {
886
+ return false;
887
+ }
888
+ if (operation.type === "height") {
889
+ const res = this.data.config.heightmapResolution;
890
+ this.data.heightmap[operation.gridZ * res + operation.gridX] = operation.newValue;
891
+ }
892
+ this.undoStack.push(operation);
893
+ this.data.metadata.modifiedAt = Date.now();
894
+ return true;
895
+ }
896
+ // ─── Serialization ─────────────────────────────────────
897
+ getData() {
898
+ return this.data;
899
+ }
900
+ setData(data) {
901
+ this.data = data;
902
+ this.undoStack = [];
903
+ this.redoStack = [];
904
+ }
905
+ serialize() {
906
+ return JSON.stringify({
907
+ ...this.data,
908
+ heightmap: Array.from(this.data.heightmap),
909
+ splatmaps: this.data.splatmaps.map((s) => Array.from(s)),
910
+ holemap: Array.from(this.data.holemap),
911
+ detailMaps: this.data.detailMaps.map((d) => Array.from(d))
912
+ });
913
+ }
914
+ static deserialize(json) {
915
+ const data = JSON.parse(json);
916
+ const terrain = new TerrainSystem(data.config);
917
+ terrain.data = {
918
+ ...data,
919
+ heightmap: new Float32Array(data.heightmap),
920
+ splatmaps: data.splatmaps.map((s) => new Uint8Array(s)),
921
+ holemap: new Uint8Array(data.holemap),
922
+ detailMaps: data.detailMaps.map((d) => new Uint8Array(d))
923
+ };
924
+ return terrain;
925
+ }
926
+ // ─── Export Heightmap ──────────────────────────────────
927
+ exportHeightmapAsRAW() {
928
+ const res = this.data.config.heightmapResolution;
929
+ const buffer = new ArrayBuffer(res * res * 2);
930
+ const view = new Uint16Array(buffer);
931
+ for (let i = 0; i < this.data.heightmap.length; i++) {
932
+ view[i] = Math.round(this.data.heightmap[i] * 65535);
933
+ }
934
+ return buffer;
935
+ }
936
+ importHeightmapFromRAW(buffer, is16bit = true) {
937
+ const res = this.data.config.heightmapResolution;
938
+ if (is16bit) {
939
+ const view = new Uint16Array(buffer);
940
+ const expectedSize = res * res;
941
+ if (view.length !== expectedSize) {
942
+ throw new Error(`RAW size mismatch: expected ${expectedSize}, got ${view.length}`);
943
+ }
944
+ for (let i = 0; i < view.length; i++) {
945
+ this.data.heightmap[i] = view[i] / 65535;
946
+ }
947
+ } else {
948
+ const view = new Uint8Array(buffer);
949
+ const expectedSize = res * res;
950
+ if (view.length !== expectedSize) {
951
+ throw new Error(`RAW size mismatch: expected ${expectedSize}, got ${view.length}`);
952
+ }
953
+ for (let i = 0; i < view.length; i++) {
954
+ this.data.heightmap[i] = view[i] / 255;
955
+ }
956
+ }
957
+ this.data.metadata.modifiedAt = Date.now();
958
+ }
959
+ exportSplatmapAsPNG(splatmapIndex) {
960
+ if (splatmapIndex >= this.data.splatmaps.length) {
961
+ return null;
962
+ }
963
+ const res = this.data.config.splatmapResolution;
964
+ const splatmap = this.data.splatmaps[splatmapIndex];
965
+ const imageData = new ImageData(res, res);
966
+ for (let i = 0; i < splatmap.length; i++) {
967
+ imageData.data[i] = splatmap[i];
968
+ }
969
+ return imageData;
970
+ }
1077
971
  }
1078
- // ============================================================
1079
- // Factory Functions
1080
- // ============================================================
1081
972
  function createTerrain(config) {
1082
- return new TerrainSystem(config);
973
+ return new TerrainSystem(config);
1083
974
  }
1084
975
  function createFlatTerrain(config) {
1085
- const terrain = new TerrainSystem(config);
1086
- // Already flat (heights = 0)
1087
- return terrain;
976
+ const terrain = new TerrainSystem(config);
977
+ return terrain;
1088
978
  }
1089
979
  function createHillyTerrain(config) {
1090
- const terrain = new TerrainSystem(config);
1091
- terrain.generatePerlinTerrain(0.005, 6, 0.5);
1092
- return terrain;
980
+ const terrain = new TerrainSystem(config);
981
+ terrain.generatePerlinTerrain(5e-3, 6, 0.5);
982
+ return terrain;
1093
983
  }
1094
984
  function createMountainousTerrain(config) {
1095
- const terrain = new TerrainSystem(config);
1096
- terrain.generateDiamondSquare(0.6);
1097
- terrain.applyHydraulicErosion(30000);
1098
- return terrain;
985
+ const terrain = new TerrainSystem(config);
986
+ terrain.generateDiamondSquare(0.6);
987
+ terrain.applyHydraulicErosion(3e4);
988
+ return terrain;
1099
989
  }
1100
990
  function createIslandTerrain(config) {
1101
- const terrain = new TerrainSystem(config);
1102
- const res = terrain.getData().config.heightmapResolution;
1103
- const data = terrain.getData();
1104
- // Generate hills
1105
- terrain.generatePerlinTerrain(0.008, 5, 0.5);
1106
- // Apply radial falloff for island shape
1107
- const centerX = res / 2;
1108
- const centerZ = res / 2;
1109
- const maxDist = Math.min(centerX, centerZ) * 0.9;
1110
- for (let z = 0; z < res; z++) {
1111
- for (let x = 0; x < res; x++) {
1112
- const dx = x - centerX;
1113
- const dz = z - centerZ;
1114
- const dist = Math.sqrt(dx * dx + dz * dz);
1115
- const falloff = Math.max(0, 1 - dist / maxDist);
1116
- const smoothFalloff = falloff * falloff * (3 - 2 * falloff); // Smoothstep
1117
- data.heightmap[z * res + x] *= smoothFalloff;
1118
- }
1119
- }
1120
- terrain.setData(data);
1121
- return terrain;
991
+ const terrain = new TerrainSystem(config);
992
+ const res = terrain.getData().config.heightmapResolution;
993
+ const data = terrain.getData();
994
+ terrain.generatePerlinTerrain(8e-3, 5, 0.5);
995
+ const centerX = res / 2;
996
+ const centerZ = res / 2;
997
+ const maxDist = Math.min(centerX, centerZ) * 0.9;
998
+ for (let z = 0; z < res; z++) {
999
+ for (let x = 0; x < res; x++) {
1000
+ const dx = x - centerX;
1001
+ const dz = z - centerZ;
1002
+ const dist = Math.sqrt(dx * dx + dz * dz);
1003
+ const falloff = Math.max(0, 1 - dist / maxDist);
1004
+ const smoothFalloff = falloff * falloff * (3 - 2 * falloff);
1005
+ data.heightmap[z * res + x] *= smoothFalloff;
1006
+ }
1007
+ }
1008
+ terrain.setData(data);
1009
+ return terrain;
1122
1010
  }
1123
-
1124
- export { DEFAULT_BRUSH, DEFAULT_TERRAIN_CONFIG, TerrainSystem, createFlatTerrain, createGrassDetail, createHillyTerrain, createIslandTerrain, createMountainousTerrain, createTerrain, createTerrainLayer, createTreePrototype };
1011
+ export {
1012
+ DEFAULT_BRUSH,
1013
+ DEFAULT_TERRAIN_CONFIG,
1014
+ TerrainSystem,
1015
+ createFlatTerrain,
1016
+ createGrassDetail,
1017
+ createHillyTerrain,
1018
+ createIslandTerrain,
1019
+ createMountainousTerrain,
1020
+ createTerrain,
1021
+ createTerrainLayer,
1022
+ createTreePrototype
1023
+ };