data-primals-engine 1.0.0

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.
@@ -0,0 +1,189 @@
1
+ import {Event} from "./events.js";
2
+ import chalk from "chalk";
3
+ import util from "node:util"
4
+
5
+ export const GameObject = {
6
+ Create: (name = 'untitled', params = {}) => {
7
+ const go = {
8
+ name,
9
+ components: [], // Tableau pour stocker les composants
10
+ addComponent : function(Component, ...args) {
11
+ if (!(Component.prototype instanceof Behaviour)) {
12
+ throw new Error("Le composant doit hériter de la classe Behavior.");
13
+ }
14
+ const component = new Component(this, ...args);
15
+ this.components.push(component);
16
+ return component;
17
+ },
18
+ getComponent: function(Component) {
19
+ return this.components.find(c => c instanceof Component);
20
+ },
21
+ getComponents: function(Component) {
22
+ return this.components.filter(c => c instanceof Component);
23
+ },
24
+ on : (event, callback) => {
25
+ Event.Listen("GameObject." + event, callback);
26
+ },
27
+ off: (event, callback) => {
28
+ Event.RemoveCallback("GameObject." + event, callback);
29
+ }
30
+ };
31
+ Object.assign(go, params);
32
+ return go;
33
+ }
34
+ }
35
+ // Behavior.js
36
+ class Behaviour {
37
+ constructor(gameObject) {
38
+ this.gameObject = gameObject;
39
+ Event.Trigger("GameObject."+(this.constructor.name)+".init", "system", "calls", this);
40
+ }
41
+
42
+ // Méthodes communes à tous les comportements (exemples)
43
+ onEnable() {
44
+ // Logique d'initialisation du comportement
45
+ }
46
+
47
+ onDisable() {
48
+ // Logique de nettoyage du comportement
49
+ }
50
+ }
51
+ // MovableBehavior.js
52
+ export class MovableBehaviour extends Behaviour {
53
+ constructor(gameObject, speed = 5) {
54
+ super(gameObject);
55
+ this.speed = speed;
56
+ }
57
+
58
+ update() {
59
+ const { x, y } = this.gameObject;
60
+ // Logique de déplacement (exemple)
61
+ this.gameObject.x += this.speed;
62
+ }
63
+ }
64
+
65
+ // UsableBehavior.js
66
+ export class UsableBehaviour extends Behaviour {
67
+ constructor(gameObject) {
68
+ super(gameObject);
69
+ }
70
+
71
+ use() {
72
+ Event.Trigger("GameObject.UsableBehavior.use", "system", "calls", this);
73
+ // Logique d'utilisation (exemple)
74
+ console.log(this.gameObject.name + " a été utilisé !");
75
+ }
76
+ }
77
+
78
+ const pilote = GameObject.Create("Pilote");
79
+
80
+ // Exemple d'attachement de comportements
81
+ pilote.addComponent(MovableBehaviour, 10);
82
+ pilote.addComponent(UsableBehaviour);
83
+
84
+ // Accéder et utiliser les composants
85
+ const movable = pilote.getComponent(MovableBehaviour);
86
+ if (movable) {
87
+ movable.update();
88
+ }
89
+ const usable = pilote.getComponent(UsableBehaviour);
90
+ if (usable) {
91
+ usable.use();
92
+ }
93
+
94
+
95
+ export class Logger extends Behaviour {
96
+ constructor(gameObject) {
97
+ super(gameObject);
98
+ }
99
+
100
+ trace(level, ...args) {
101
+ const message = args.map(arg => {
102
+ // 1. Gérer null et undefined en premier
103
+ if (arg === undefined) {
104
+ return 'undefined';
105
+ }
106
+ if (arg === null) {
107
+ return 'null';
108
+ }
109
+
110
+ // 2. Gérer les erreurs de manière plus sûre
111
+ // Utilise le duck-typing si instanceof échoue mais que l'objet ressemble à une erreur
112
+ if (typeof arg === 'object' && (arg instanceof Error || (arg.message && arg.stack))) {
113
+ try {
114
+ // Accès sécurisé aux propriétés
115
+ const name = arg.name || 'Error';
116
+ const msg = arg.message || String(arg); // Fallback si .message n'existe pas
117
+ const stack = arg.stack || '';
118
+ // Optionnel: Limiter la longueur de la stack trace
119
+ const shortStack = stack.split('\n').slice(0, 10).join('\n'); // Limite à 10 lignes
120
+ return `${name}: ${msg}\n${shortStack}${stack.length > shortStack.length ? '...' : ''}`;
121
+ } catch (formatError) {
122
+ // Fallback si même l'accès aux propriétés de base échoue
123
+ return '[Error (formatting failed)]';
124
+ }
125
+ }
126
+
127
+ // 3. Gérer les autres objets (avec inspection sécurisée)
128
+ if (typeof arg === 'object') {
129
+ try {
130
+ // Utiliser util.inspect avec une profondeur contrôlée pour éviter les erreurs/trop de logs
131
+ return util.inspect(arg, { depth: 2, colors: false }); // Ajustez la profondeur si nécessaire
132
+ } catch (inspectError) {
133
+ // Attrape les erreurs pendant l'inspection (références circulaires, getters problématiques)
134
+ return `[Object (inspect error: ${inspectError.message})]`;
135
+ }
136
+ }
137
+
138
+ // 4. Fallback pour les types primitifs (string, number, boolean, etc.)
139
+ try {
140
+ return String(arg);
141
+ } catch (stringError) {
142
+ // Très improbable, mais pour être exhaustif
143
+ return '[Value (string conversion failed)]';
144
+ }
145
+ }).join(' ');
146
+
147
+ const timestamp = new Date().toISOString(); // Ou votre format préféré
148
+ // Utilisez console.log, console.error, ou votre mécanisme de sortie de log
149
+ const msg = `[${timestamp}] [${level}] ${message}`;
150
+ return msg
151
+ }
152
+ info(...args) {
153
+ console.log(chalk.green(this.trace("info", ...args)));
154
+ Event.Trigger("GameObject.LoggableBehaviour.info", "log", "info", ...args, this);
155
+ }
156
+ debug(...args) {
157
+ console.log(chalk.yellow(this.trace("debug", ...args)));
158
+ Event.Trigger("GameObject.LoggableBehaviour.debug", "log", "debug", ...args, this);
159
+ }
160
+ warn(...args) {
161
+ console.warn(chalk.magenta(this.trace("warn", ...args)));
162
+ Event.Trigger("GameObject.LoggableBehaviour.warn", "log", "warn", ...args, this);
163
+ }
164
+ error(...args) {
165
+ console.error(chalk.red(this.trace("error", ...args)));
166
+ Event.Trigger("GameObject.LoggableBehaviour.error", "log", "error", ...args, this);
167
+ }
168
+ critical(...args) {
169
+ console.error(chalk.red(chalk.bold(this.trace("critical", ...args))));
170
+ Event.Trigger("GameObject.LoggableBehaviour.critical", "log", "critical", ...args, this);
171
+ }
172
+
173
+ }
174
+
175
+ export class BenchmarkTool extends Behaviour{
176
+ constructor(gameObject) {
177
+ super(gameObject);
178
+ this.time = 0;
179
+ }
180
+ start() {
181
+ this.time = performance.now();
182
+ }
183
+ stop() {
184
+ const stopTime = performance.now();
185
+ const elapsedTime = stopTime - this.time; // Calcule le temps écoulé une seule fois
186
+ console.log(`Time elapsed: ${elapsedTime.toFixed(4)}ms`); // Utilisation de template literals pour une meilleure lisibilité
187
+ return elapsedTime; // Retourne le temps écoulé (pas besoin de le recalculer)
188
+ }
189
+ }