]> git.lizzy.rs Git - dragonblocks_alpha.git/blob - src/client/client_terrain.c
9dde1094dfa7ff9093b68459813baddb0298d4bc
[dragonblocks_alpha.git] / src / client / client_terrain.c
1 #define _GNU_SOURCE // don't worry, GNU extensions are only used when available
2 #include <dragonstd/queue.h>
3 #include <sched.h>
4 #include <stdatomic.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <pthread.h>
8 #include "client/client.h"
9 #include "client/facecache.h"
10 #include "client/client_config.h"
11 #include "client/client_node.h"
12 #include "client/client_player.h"
13 #include "client/client_terrain.h"
14 #include "client/debug_menu.h"
15 #include "client/terrain_gfx.h"
16 #include "facedir.h"
17
18 #define MAX_REQUESTS 4
19
20 Terrain *client_terrain;
21
22 static atomic_bool cancel;         // used to notify meshgen and sync thread about quit
23 static Queue meshgen_tasks;        // TerrainCHunk * queue (thread safe)
24 static pthread_t *meshgen_threads; // consumer threads for meshgen queue
25 static pthread_t sync_thread;      // this thread requests new / changed chunks from server
26 static u32 load_distance;          // load distance sent by server
27 static size_t load_chunks;         // cached number of facecache positions to process every sync step (matches load distance)
28
29 // meshgen functions
30
31 // dequeue callback to update queue state in a thread safe manner
32 static TerrainChunk *set_dequeued(TerrainChunk *chunk)
33 {
34         pthread_mutex_lock(&chunk->mtx);
35         ((TerrainChunkMeta *) chunk->extra)->queue = false;
36         pthread_mutex_unlock(&chunk->mtx);
37
38         return chunk;
39 }
40
41 // mesh generator step
42 static void meshgen_step()
43 {
44         TerrainChunk *chunk = queue_deq(&meshgen_tasks, &set_dequeued);
45
46         if (chunk)
47                 terrain_gfx_make_chunk_model(chunk);
48 }
49
50 // sync functions
51
52 // send chunk request command to server
53 static void request_chunk(v3s32 pos)
54 {
55         dragonnet_peer_send_ToServerRequestChunk(client, &(ToServerRequestChunk) {
56                 .pos = pos
57         });
58 }
59
60 // terrain synchronisation step
61 static void sync_step()
62 {
63         static u64 tick = 0;
64         static v3s32 *old_requests = NULL;
65         static size_t old_num_requests = 0;
66
67         v3f64 player_pos;
68         ClientEntity *entity = client_player_entity_local();
69
70         if (entity) {
71                 pthread_rwlock_rdlock(&entity->lock_pos_rot);
72                 player_pos = entity->data.pos;
73                 pthread_rwlock_unlock(&entity->lock_pos_rot);
74
75                 refcount_drp(&entity->rc);
76         } else {
77                 sched_yield();
78                 return;
79         }
80
81         v3s32 center = terrain_chunkp((v3s32) {player_pos.x, player_pos.y, player_pos.z});
82
83         u64 last_tick = tick++;
84
85         v3s32 *requests = malloc(MAX_REQUESTS * sizeof *requests);
86         size_t num_requests = 0;
87
88         for (size_t i = 0; i < load_chunks; i++) {
89                 v3s32 pos = v3s32_add(facecache_get(i), center);
90                 TerrainChunk *chunk = terrain_get_chunk(client_terrain, pos, false);
91
92                 if (chunk) {
93                         pthread_mutex_lock(&chunk->mtx);
94
95                         TerrainChunkMeta *meta = chunk->extra;
96                         switch (meta->state) {
97                                 case CHUNK_READY:
98                                         // re-request chunks that got back into range
99                                         if (meta->sync < last_tick)
100                                                 request_chunk(pos);
101                                         __attribute__((fallthrough));
102
103                                 case CHUNK_FRESH:
104                                         meta->state = CHUNK_READY;
105                                         meta->sync = tick;
106                                         break;
107
108                                 case CHUNK_RECIEVING:
109                                         break;
110                         }
111
112                         pthread_mutex_unlock(&chunk->mtx);
113                 } else if (num_requests < MAX_REQUESTS) {
114                         // avoid duplicate requests
115                         bool requested = false;
116
117                         for (size_t i = 0; i < old_num_requests; i++) {
118                                 if (v3s32_equals(old_requests[i], pos)) {
119                                         requested = true;
120                                         break;
121                                 }
122                         }
123
124                         if (!requested)
125                                 request_chunk(pos);
126
127                         requests[num_requests++] = pos;
128                 }
129         }
130
131         if (old_requests)
132                 free(old_requests);
133
134         old_requests = requests;
135         old_num_requests = num_requests;
136 }
137
138 // pthread routine for meshgen and sync thread
139
140 static struct LoopThread {
141         const char *name;
142         void (*step)();
143 } loop_threads[2] = {
144         {"meshgen", &meshgen_step},
145         {   "sync",    &sync_step},
146 };
147
148 static void *loop_routine(struct LoopThread *thread)
149 {
150 #ifdef __GLIBC__ // check whether bloat is enabled
151         pthread_setname_np(pthread_self(), thread->name);
152 #endif // __GLIBC__
153
154         // warning: extremely advanced logic
155         while (!cancel)
156                 thread->step();
157
158         return NULL;
159 }
160
161 // terrain callbacks
162 // note: all these functions require the chunk mutex to be locked, which is always the case when a terrain callback is invoked
163
164 // callback for initializing a newly created chunk
165 // allocate and initialize meta data
166 static void on_create_chunk(TerrainChunk *chunk)
167 {
168         TerrainChunkMeta *meta = chunk->extra = malloc(sizeof *meta);
169
170         meta->state = CHUNK_RECIEVING;
171         meta->queue = false;
172         meta->sync = 0;
173         meta->model = NULL;
174         meta->empty = false;
175         meta->has_model = false;
176         for (int i = 0; i < 6; i++)
177                 meta->depends[i] = false;
178 }
179
180 // callback for deleting a chunk
181 // free meta data
182 static void on_delete_chunk(TerrainChunk *chunk)
183 {
184         free(chunk->extra);
185 }
186
187 // callback for determining whether a chunk should be returned by terrain_get_chunk
188 // hold back chunks that have not been fully read from server yet when the create flag is not set
189 static bool on_get_chunk(TerrainChunk *chunk, bool create)
190 {
191         return create || ((TerrainChunkMeta *) chunk->extra)->state > CHUNK_RECIEVING;
192 }
193
194 // public functions
195
196 // called on startup
197 void client_terrain_init()
198 {
199         client_terrain = terrain_create();
200         client_terrain->callbacks.create_chunk = &on_create_chunk;
201         client_terrain->callbacks.delete_chunk = &on_delete_chunk;
202         client_terrain->callbacks.get_chunk    = &on_get_chunk;
203         client_terrain->callbacks.delete_node  = &client_node_delete;
204
205         cancel = false;
206         queue_ini(&meshgen_tasks);
207
208         client_terrain_set_load_distance(10); // some initial fuck idk just in case server is stupid
209
210         sync_thread = 0;
211         meshgen_threads = malloc(sizeof *meshgen_threads * client_config.meshgen_threads);
212         for (unsigned int i = 0; i < client_config.meshgen_threads; i++)
213                 meshgen_threads[i] = 0; // but why???
214 }
215
216 // called on shutdown
217 void client_terrain_deinit()
218 {
219         queue_clr(&meshgen_tasks, NULL, NULL, NULL);
220         terrain_delete(client_terrain);
221 }
222
223 // start meshgen and sync threads
224 void client_terrain_start()
225 {
226         for (unsigned int i = 0; i < client_config.meshgen_threads; i++)
227                 pthread_create(&meshgen_threads[i], NULL, (void *) &loop_routine, &loop_threads[0]);
228
229         pthread_create(&sync_thread, NULL, (void *) &loop_routine, &loop_threads[1]);
230 }
231
232 // stop meshgen and sync threads
233 void client_terrain_stop()
234 {
235         cancel = true;
236         queue_cnl(&meshgen_tasks);
237
238         for (unsigned int i = 0; i < client_config.meshgen_threads; i++)
239                 if (meshgen_threads[i])
240                         pthread_join(meshgen_threads[i], NULL);
241         free(meshgen_threads);
242
243         if (sync_thread)
244                 pthread_join(sync_thread, NULL);
245 }
246
247 // update load distance
248 void client_terrain_set_load_distance(u32 dist)
249 {
250         load_distance = dist;
251         load_chunks = facecache_count(load_distance);
252         debug_menu_changed(ENTRY_LOAD_DISTANCE);
253 }
254
255 // return load distance
256 u32 client_terrain_get_load_distance()
257 {
258         return load_distance;
259 }
260
261 // called when a chunk was recieved from server
262 void client_terrain_chunk_received(TerrainChunk *chunk)
263 {
264         pthread_mutex_lock(&chunk->mtx);
265         TerrainChunkMeta *meta = chunk->extra;
266
267         if (meta->state == CHUNK_RECIEVING)
268                 meta->state = CHUNK_FRESH;
269
270         client_terrain_meshgen_task(chunk, true);
271         pthread_mutex_unlock(&chunk->mtx);
272
273         for (int i = 0; i < 6; i++) {
274                 TerrainChunk *neighbor = terrain_get_chunk(client_terrain,
275                         v3s32_sub(chunk->pos, facedir[i]), false);
276                 if (!neighbor)
277                         continue;
278
279                 pthread_mutex_lock(&neighbor->mtx);
280                 TerrainChunkMeta *neighbor_meta = neighbor->extra;
281                 if (neighbor_meta->depends[i])
282                         client_terrain_meshgen_task(neighbor, true);
283                 pthread_mutex_unlock(&neighbor->mtx);
284         }
285 }
286
287 // enqueue chunk to mesh update queue
288 void client_terrain_meshgen_task(TerrainChunk *chunk, bool changed)
289 {
290         TerrainChunkMeta *meta = chunk->extra;
291         if (meta->queue)
292                 return;
293
294         if (meta->empty) {
295                 meta->has_model = true;
296
297                 if (meta->model) {
298                         meta->model->flags.delete = 1;
299                         meta->model = NULL;
300                 }
301         } else {
302                 meta->queue = true;
303
304                 if (meta->has_model && changed)
305                         queue_ppd(&meshgen_tasks, chunk);
306                 else
307                         queue_enq(&meshgen_tasks, chunk);
308         }
309 }