strichmaennchen git · main
git clone https://git.christianimmanuel.de/games/strichmaennchen.gitwget https://git.christianimmanuel.de/games/strichmaennchen/archive/strichmaennchen.tar.gztime.c raw
#include "time.h"
#include <math.h>
#include <stdlib.h>
float fmodf(float x, float y);
float cosf(float x);
float sinf(float x);
float fmaxf(float x, float y);
#define M_PI 3.14159265358979323846
float Time_delta(Uint64* prev_ticks) {
Uint64 now = SDL_GetTicks();
float dt = (now - *prev_ticks) / 1000.0f;
*prev_ticks = now;
return dt;
}
Time* Time_init(float timeScale) {
Time* t = malloc(sizeof(Time));
if (!t) return NULL;
//t->hours = 12.0f;
t->hours = 13.0f;
t->minutes = 0.0f;
t->seconds = 0.0f;
t->timeScale = timeScale;
t->dayStart = 7.0f; // 07:00
t->dayEnd = 21.0f; // 21:00
Time_computeSunPosition(t);
return t;
}
void Time_update(Time* t, float deltaSeconds) {
float scaled = deltaSeconds * t->timeScale;
t->seconds += scaled;
if (t->seconds >= 60.0f) {
t->minutes += (int)(t->seconds / 60.0f);
t->seconds = fmodf(t->seconds, 60.0f);
}
if (t->minutes >= 60.0f) {
t->hours += (int)(t->minutes / 60.0f);
t->minutes = fmodf(t->minutes, 60.0f);
}
if (t->hours >= 24.0f) t->hours -= 24.0f;
Time_computeSunPosition(t);
}
float Time_getFractionOfDay(const Time* t) {
return (t->hours + t->minutes/60.0f + t->seconds/3600.0f) / 24.0f;
}
void Time_computeSunPosition(Time* t) {
//
float hour = t->hours + t->minutes/60.0f + t->seconds/3600.0f;
float dayFraction = (hour - t->dayStart) / (t->dayEnd - t->dayStart); // 0..1 during day
float nightFraction = (hour < t->dayStart)
? (hour + 24.0f - t->dayEnd) / (24.0f - (t->dayEnd - t->dayStart))
: (hour - t->dayEnd) / (24.0f - (t->dayEnd - t->dayStart));
// Continuous sun angle
float angle;
if (hour >= t->dayStart && hour <= t->dayEnd) {
angle = dayFraction * M_PI; // day: sunrise → sunset
} else {
angle = nightFraction * M_PI + M_PI; // night: continue the half-circle downward
}
// Sun points along X/Y plane
t->sunDirection = (Vec3){ cosf(angle), sinf(angle), 0.0f };
// Sun color: interpolate warm colors at sunrise/sunset
float intensity = fmaxf(t->sunDirection.y, 0.0f);
t->sunColor.x = 1.0f * intensity;
t->sunColor.y = 0.95f * intensity;
t->sunColor.z = 0.8f * intensity;
// ambient color
t->ambientColor.x = 0.1f + 0.2f * intensity;
t->ambientColor.y = 0.1f + 0.2f * intensity;
t->ambientColor.z = 0.15f + 0.2f * intensity;
t->dayFactor = intensity;
}
void Time_destroy(Time* t) {
free(t);
}