Debian Codegraph @

src/cdogs/particle.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (c) 2014-2017, 2019-2021, 2024 Cong Xu
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10 Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
12 Redistributions in binary form must reproduce the above copyright notice,
13 this list of conditions and the following disclaimer in the documentation
14 and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 POSSIBILITY OF SUCH DAMAGE.
27 */
28 #include "particle.h"
29
30 #include "campaigns.h"
31 #include "collision/collision.h"
32 #include "font.h"
33 #include "game_events.h"
34 #include "json_utils.h"
35 #include "log.h"
36 #include "objs.h"
37
38 ParticleClasses gParticleClasses;
39 CArray gParticles;
40 #define MAX_PARTICLES 4096
41
42 #define VERSION 3
43
44 // Particles get darker when below this height
45 #define PARTICLE_DARKEN_Z BULLET_Z
46
47 ParticleType StrParticleType(const char *s)
48 {
49 S2T(PARTICLE_PIC, "Pic");
50 S2T(PARTICLE_TEXT, "Text");
51 return PARTICLE_PIC;
52 }
53
54 static void LoadParticleClass(
55 ParticleClass *c, json_t *node, const int version);
56 void ParticleClassesInit(ParticleClasses *classes, const char *filename)
57 {
58 CArrayInit(&classes->Classes, sizeof(ParticleClass));
59 CArrayInit(&classes->CustomClasses, sizeof(ParticleClass));
60
61 char buf[CDOGS_PATH_MAX];
62 GetDataFilePath(buf, filename);
63 FILE *f = fopen(buf, "r");
64 json_t *root = NULL;
65 if (f == NULL)
66 {
67 LOG(LM_MAIN, LL_ERROR, "Error: cannot load particles file %s", buf);
68 goto bail;
69 }
70 enum json_error e = json_stream_parse(f, &root);
71 if (e != JSON_OK)
72 {
73 LOG(LM_MAIN, LL_ERROR, "Error parsing particles file %s", buf);
74 goto bail;
75 }
76 ParticleClassesLoadJSON(&classes->Classes, root);
77
78 bail:
79 if (f != NULL)
80 {
81 fclose(f);
82 }
83 json_free_value(&root);
84 }
85 void ParticleClassesLoadJSON(CArray *classes, json_t *root)
86 {
87 int version;
88 LoadInt(&version, root, "Version");
89 if (version > VERSION || version <= 0)
90 {
91 CASSERT(false, "cannot read particles file version");
92 return;
93 }
94
95 json_t *particlesNode = json_find_first_label(root, "Particles")->child;
96 for (json_t *child = particlesNode->child; child; child = child->next)
97 {
98 ParticleClass c;
99 LoadParticleClass(&c, child, version);
100 CArrayPushBack(classes, &c);
101 }
102 }
103 void ParticleClassesTerminate(ParticleClasses *classes)
104 {
105 ParticleClassesClear(&classes->Classes);
106 CArrayTerminate(&classes->Classes);
107 ParticleClassesClear(&classes->CustomClasses);
108 CArrayTerminate(&classes->CustomClasses);
109 }
110 void ParticleClassesClear(CArray *classes)
111 {
112 for (int i = 0; i < (int)classes->size; i++)
113 {
114 ParticleClass *c = CArrayGet(classes, i);
115 CFREE(c->Name);
116 }
117 CArrayClear(classes);
118 }
119 static void LoadParticleClass(
120 ParticleClass *c, json_t *node, const int version)
121 {
122 memset(c, 0, sizeof *c);
123 char *tmp;
124
125 c->Name = GetString(node, "Name");
126
127 c->Type = PARTICLE_PIC;
128 if (version < 2)
129 {
130 c->u.Pic.Mask = colorWhite;
131 if (json_find_first_label(node, "Sprites"))
132 {
133 tmp = GetString(node, "Sprites");
134 c->u.Pic.Type = PICTYPE_DIRECTIONAL;
135 c->u.Pic.u.Sprites =
136 &PicManagerGetSprites(&gPicManager, tmp)->pics;
137 CFREE(tmp);
138 }
139 else
140 {
141 LoadPic(&c->u.Pic.u.Pic, node, "Pic");
142 }
143 if (json_find_first_label(node, "Mask"))
144 {
145 tmp = GetString(node, "Mask");
146 c->u.Pic.Mask = StrColor(tmp);
147 CFREE(tmp);
148 }
149 int ticksPerFrame = 0;
150 LoadInt(&ticksPerFrame, node, "TicksPerFrame");
151 if (ticksPerFrame > 0)
152 {
153 c->u.Pic.Type = PICTYPE_ANIMATED;
154 c->u.Pic.u.Animated.Sprites = c->u.Pic.u.Sprites;
155 c->u.Pic.u.Animated.TicksPerFrame = ticksPerFrame;
156 }
157 }
158 else
159 {
160 tmp = NULL;
161 LoadStr(&tmp, node, "Type");
162 if (tmp != NULL)
163 {
164 c->Type = StrParticleType(tmp);
165 CFREE(tmp);
166 }
167 switch (c->Type)
168 {
169 case PARTICLE_PIC:
170 CPicLoadJSON(&c->u.Pic, json_find_first_label(node, "Pic")->child);
171 break;
172 case PARTICLE_TEXT:
173 c->u.Text.Mask = colorWhite;
174 if (version <= 2)
175 {
176 tmp = NULL;
177 LoadStr(&tmp, node, "TextMask");
178 if (tmp != NULL)
179 {
180 c->u.Text.Mask = StrColor(tmp);
181 }
182 CFREE(tmp);
183 }
184 else
185 {
186 if (json_find_first_label(node, "Text"))
187 {
188 json_t *text = json_find_first_label(node, "Text")->child;
189 tmp = NULL;
190 LoadStr(&tmp, text, "Mask");
191 if (tmp != NULL)
192 {
193 c->u.Text.Mask = StrColor(tmp);
194 }
195 CFREE(tmp);
196
197 LoadStr(&c->u.Text.Value, text, "Value");
198 }
199 }
200 break;
201 default:
202 break;
203 }
204 }
205
206 if (json_find_first_label(node, "Range"))
207 {
208 LoadInt(&c->RangeLow, node, "Range");
209 c->RangeHigh = c->RangeLow;
210 }
211 if (json_find_first_label(node, "RangeLow"))
212 {
213 LoadInt(&c->RangeLow, node, "RangeLow");
214 }
215 if (json_find_first_label(node, "RangeHigh"))
216 {
217 LoadInt(&c->RangeHigh, node, "RangeHigh");
218 }
219 c->RangeLow = MIN(c->RangeLow, c->RangeHigh);
220 c->RangeHigh = MAX(c->RangeLow, c->RangeHigh);
221 LoadFloat(&c->GravityFactor, node, "GravityFactor");
222 LoadBool(&c->HitsWalls, node, "HitsWalls");
223 c->Bounces = true;
224 LoadBool(&c->Bounces, node, "Bounces");
225 LoadFloat(&c->BounceFriction, node, "BounceFriction");
226 c->WallBounces = true;
227 LoadBool(&c->WallBounces, node, "WallBounces");
228 LoadBool(&c->ZDarken, node, "ZDarken");
229 LoadBool(&c->DrawBelow, node, "DrawBelow");
230 LoadBool(&c->DrawAbove, node, "DrawAbove");
231 }
232
233 const ParticleClass *StrParticleClass(
234 const ParticleClasses *classes, const char *name)
235 {
236 if (name == NULL || strlen(name) == 0)
237 {
238 return NULL;
239 }
240 CA_FOREACH(const ParticleClass, c, classes->CustomClasses)
241 if (strcmp(c->Name, name) == 0)
242 {
243 return c;
244 }
245 CA_FOREACH_END()
246 CA_FOREACH(const ParticleClass, c, classes->Classes)
247 if (strcmp(c->Name, name) == 0)
248 {
249 return c;
250 }
251 CA_FOREACH_END()
252 LOG(LM_MAIN, LL_ERROR, "Cannot find particle class %s", name);
253 return NULL;
254 }
255
256 void ParticlesInit(CArray *particles)
257 {
258 CArrayInit(particles, sizeof(Particle));
259 CArrayReserve(particles, 256);
260 }
261 void ParticlesTerminate(CArray *particles)
262 {
263 for (int i = 0; i < (int)particles->size; i++)
264 {
265 Particle *p = CArrayGet(particles, i);
266 if (p->isInUse)
267 {
268 ParticleDestroy(particles, i);
269 }
270 }
271 CArrayTerminate(particles);
272 }
273
274 static bool ParticleUpdate(Particle *p, const int ticks);
275 void ParticlesUpdate(CArray *particles, const int ticks)
276 {
277 int maxParticleAge = -1;
278 int maxParticleId = -1;
279 int numParticles = 0;
280 CA_FOREACH(Particle, p, *particles)
281 if (!p->isInUse)
282 {
283 continue;
284 }
285 if (!ParticleUpdate(p, ticks))
286 {
287 GameEvent e = GameEventNew(GAME_EVENT_PARTICLE_REMOVE);
288 e.u.ParticleRemoveId = _ca_index;
289 GameEventsEnqueue(&gGameEvents, e);
290 }
291 else
292 {
293 if (p->Count > maxParticleAge)
294 {
295 maxParticleAge = p->Count;
296 maxParticleId = _ca_index;
297 }
298 numParticles++;
299 }
300 CA_FOREACH_END()
301 // Remove oldest particle if we have too many
302 if (numParticles > MAX_PARTICLES && maxParticleId >= 0)
303 {
304 GameEvent e = GameEventNew(GAME_EVENT_PARTICLE_REMOVE);
305 e.u.ParticleRemoveId = maxParticleId;
306 GameEventsEnqueue(&gGameEvents, e);
307 }
308 }
309
310 typedef struct
311 {
312 const Thing *Obj;
313 struct vec2 ColPos;
314 struct vec2 ColNormal;
315 float ColPosDist2;
316 } HitWallData;
317 static bool CheckWall(const struct vec2i tilePos);
318 static bool HitWallFunc(
319 const struct vec2i tilePos, void *data, const struct vec2 col,
320 const struct vec2 normal);
321 static bool ParticleUpdate(Particle *p, const int ticks)
322 {
323 switch (p->Class->Type)
324 {
325 case PARTICLE_PIC:
326 CPicUpdate(&p->u.Pic, ticks);
327 break;
328 default:
329 break;
330 }
331 p->Count += ticks;
332 const struct vec2 startPos = p->Pos;
333 for (int i = 0; i < ticks; i++)
334 {
335 p->Pos = svec2_add(p->Pos, p->thing.Vel);
336 p->Z += p->DZ;
337 if (p->Class->GravityFactor != 0)
338 {
339 if (p->Z <= 0)
340 {
341 p->Z = 0;
342 if (p->Class->Bounces)
343 {
344 p->DZ = -p->DZ / 2;
345 p->thing.Vel = svec2_scale(
346 p->thing.Vel, 1 - p->Class->BounceFriction);
347 }
348 else
349 {
350 p->DZ = 0;
351 }
352 }
353 else
354 {
355 p->DZ -= p->Class->GravityFactor;
356 }
357 if (fabsf(p->DZ) < fabs(p->Class->GravityFactor) &&
358 nearly_equal(p->Z, 0, 0.1f))
359 {
360 p->thing.Vel = svec2_zero();
361 p->Spin = 0;
362 // Fell to ground, draw below
363 p->thing.flags |= THING_DRAW_BELOW;
364 break;
365 }
366 }
367 }
368 // Wall collision, bounce off walls
369 if (!svec2_is_zero(p->thing.Vel) && p->Class->HitsWalls)
370 {
371 const CollisionParams params = {
372 0, COLLISIONTEAM_NONE, IsPVP(gCampaign.Entry.Mode), false};
373 HitWallData data = {&p->thing, svec2_zero(), svec2_zero(), -1};
374 OverlapThings(
375 &p->thing, startPos, p->thing.Vel, p->thing.size, params, NULL,
376 NULL, CheckWall, HitWallFunc, &data);
377 if (data.ColPosDist2 >= 0)
378 {
379 if (p->Class->WallBounces)
380 {
381 GetWallBouncePosVel(
382 startPos, p->thing.Vel, data.ColPos, data.ColNormal,
383 &p->Pos, &p->thing.Vel);
384 }
385 else
386 {
387 p->thing.Vel = svec2_zero();
388 }
389 }
390 }
391 if (!MapTryMoveThing(&gMap, &p->thing, p->Pos))
392 {
393 // Out of map; destroy
394 return false;
395 }
396
397 // Spin
398 p->Angle += p->Spin;
399 if (p->Angle > 2 * MPI)
400 {
401 p->Angle -= 2 * MPI;
402 }
403 if (p->Angle < 0)
404 {
405 p->Angle += 2 * MPI;
406 }
407
408 return p->Count <= p->Range;
409 }
410 static void SetClosestCollision(
411 HitWallData *data, const struct vec2 col, const struct vec2 normal);
412 static bool CheckWall(const struct vec2i tilePos)
413 {
414 const Tile *t = MapGetTile(&gMap, tilePos);
415 return t == NULL || TileIsShootable(t);
416 }
417 static bool HitWallFunc(
418 const struct vec2i tilePos, void *data, const struct vec2 col,
419 const struct vec2 normal)
420 {
421 UNUSED(tilePos);
422 HitWallData *hData = data;
423 SetClosestCollision(hData, col, normal);
424 return true;
425 }
426 static void SetClosestCollision(
427 HitWallData *data, const struct vec2 col, const struct vec2 normal)
428 {
429 // Choose the best collision point (i.e. closest to origin)
430 const float d2 = svec2_distance_squared(col, data->Obj->Pos);
431 if (data->ColPosDist2 < 0 || d2 < data->ColPosDist2)
432 {
433 data->ColPos = col;
434 data->ColPosDist2 = d2;
435 data->ColNormal = normal;
436 }
437 }
438
439 static void DrawParticle(
440 const struct vec2i pos, const ThingDrawFuncData *data);
441 int ParticleAdd(CArray *particles, const AddParticle add)
442 {
443 // Find an empty slot in list
444 Particle *p = NULL;
445 int i;
446 for (i = 0; i < (int)particles->size; i++)
447 {
448 Particle *pSlot = CArrayGet(particles, i);
449 if (!pSlot->isInUse)
450 {
451 p = pSlot;
452 break;
453 }
454 }
455 // If no empty slots, add a new one
456 if (p == NULL)
457 {
458 Particle pNew;
459 memset(&pNew, 0, sizeof pNew);
460 CArrayPushBack(particles, &pNew);
461 i = (int)particles->size - 1;
462 p = CArrayGet(particles, i);
463 }
464 memset(p, 0, sizeof *p);
465 p->Class = add.Class;
466 switch (p->Class->Type)
467 {
468 case PARTICLE_PIC:
469 CPicCopyPic(&p->u.Pic, &p->Class->u.Pic);
470 break;
471 case PARTICLE_TEXT:
472 CSTRDUP(p->u.Text, add.Text);
473 break;
474 default:
475 break;
476 }
477 p->ActorUID = add.ActorUID;
478 p->Pos = add.Pos;
479 p->Z = (float)add.Z;
480 p->Angle = add.Angle;
481 p->DZ = (float)add.DZ;
482 p->Spin = add.Spin;
483 p->Range = RAND_INT(add.Class->RangeLow, add.Class->RangeHigh);
484 p->isInUse = true;
485 p->thing.Pos.x = p->thing.Pos.y = -1;
486 p->thing.Vel = add.Vel;
487 p->thing.kind = KIND_PARTICLE;
488 p->thing.id = i;
489 p->thing.drawFunc = DrawParticle;
490 p->thing.drawData.MobObjId = i;
491 p->thing.drawData.Scale =
492 svec2_is_zero(add.DrawScale) ? svec2_one() : add.DrawScale;
493 if (!ColorEquals(add.Mask, colorTransparent))
494 {
495 p->u.Pic.Mask = add.Mask;
496 }
497 if (p->Class->DrawBelow)
498 {
499 p->thing.flags |= THING_DRAW_BELOW;
500 }
501 if (p->Class->DrawAbove)
502 {
503 p->thing.flags |= THING_DRAW_ABOVE;
504 }
505 MapTryMoveThing(&gMap, &p->thing, add.Pos);
506 return i;
507 }
508 void ParticleDestroy(CArray *particles, const int id)
509 {
510 Particle *p = CArrayGet(particles, id);
511 if (!p->isInUse)
512 {
513 return;
514 }
515 MapRemoveThing(&gMap, &p->thing);
516 if (p->Class->Type == PARTICLE_TEXT)
517 {
518 CFREE(p->u.Text);
519 }
520 p->isInUse = false;
521 }
522
523 static void DrawParticle(const struct vec2i pos, const ThingDrawFuncData *data)
524 {
525 const Particle *p = CArrayGet(&gParticles, data->MobObjId);
526 CASSERT(p->isInUse, "Cannot draw non-existent particle");
527 // Special case: don't draw mid-air, non-falling particles
528 // if they are on an open door - this is for bulletmarks
529 if (p->Class->GravityFactor == 0 && p->Z > 0 &&
530 svec2_is_zero(p->thing.Vel))
531 {
532 const struct vec2i t = Vec2iToTile(svec2i_assign_vec2(p->Pos));
533 const Tile *tAbove = MapGetTile(&gMap, svec2i(t.x, t.y - 1));
534 if (tAbove != NULL && tAbove->Class->Type == TILE_CLASS_DOOR &&
535 !TileIsShootable(tAbove))
536 {
537 return;
538 }
539 }
540 switch (p->Class->Type)
541 {
542 case PARTICLE_PIC: {
543 CPicDrawContext c = CPicDrawContextNew();
544 c.Dir = RadiansToDirection(p->Angle);
545 const Pic *pic = CPicGetPic(&p->u.Pic, c.Dir);
546 if (p->u.Pic.Type != PICTYPE_DIRECTIONAL)
547 {
548 c.Radians = p->Angle;
549 }
550 c.Offset = svec2i(
551 pic->size.x / -2, pic->size.y / -2 - (int)(p->Z / Z_FACTOR));
552 c.Scale = data->Scale;
553 if (p->Class->ZDarken)
554 {
555 // Darken by 50% when on ground
556 const uint8_t maskF = (uint8_t)CLAMP(
557 p->Z * PARTICLE_DARKEN_Z * Z_FACTOR / 256 + 128, 128, 255);
558 const color_t mask = {maskF, maskF, maskF, 255};
559 c.Mask = mask;
560 }
561 CPicDraw(&gGraphicsDevice, &p->u.Pic, pos, &c);
562 break;
563 }
564 case PARTICLE_TEXT: {
565 FontOpts opts = FontOptsNew();
566 opts.HAlign = ALIGN_CENTER;
567 opts.Mask = p->Class->u.Text.Mask;
568 FontStrOpt(
569 p->u.Text, svec2i(pos.x, pos.y - (int)(p->Z / Z_FACTOR)), opts);
570 break;
571 }
572 default:
573 break;
574 }
575 }