-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathindex.ts
More file actions
436 lines (380 loc) · 12.2 KB
/
index.ts
File metadata and controls
436 lines (380 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import { Extension, Environment, untilExternalGlobalVariableLoaded, validGenericExtension, RuntimeEvent } from "$common";
import BlockUtility from "$root/scratch-packages/scratch-vm/src/engine/block-utility";
import { legacyFullSupport, info } from "./legacy";
const { legacyExtension, legacyDefinition } = legacyFullSupport.for<PoseFace>();
// TODO: Implement extension's health check (peripheral)
/**
* States what the video sensing activity can be set to.
*/
const VideoState = {
/** Video turned off. */
OFF: 'off',
/** Video turned on with default y axis mirroring. */
ON: 'on',
/** Video turned on without default y axis mirroring. */
ON_FLIPPED: 'on-flipped'
} as const;
/**
* Used for rounding
* @param amount
* @returns {double} a double
*/
function friendlyRound(amount) {
return parseFloat(Number(amount).toFixed(2));
}
/**
* Contains details about the Face Sensing extension
*/
type Details = {
name: "Face Sensing",
description: "Sense face movement with the camera.",
iconURL: "pose-face.png",
insetIconURL: "pose-face-small.svg",
tags: ["Dancing with AI", "Made by PRG"]
};
/**
* Contains descriptions of the blocks of the Block Sensing extension
*/
type Blocks = {
affdexGoToPart(facePart: string): void;
affdexReturnPart(coord: string, facePart: string): number;
affdexWhenExpression(expression: string): boolean;
affdexExpressionAmount(expression: string): number;
affdexIsExpression(expression: string): boolean;
affdexWhenEmotion(feeling: string): boolean;
affdexEmotionAmount(feeling: string): number;
affdexIsTopEmotion(feeling: string): boolean;
// these video blocks are present in a few different extensions, perhaps making a file just for these?
videoToggle(state: string): void;
setVideoTransparency(transparency: number): void;
}
type Affdex = {
PhotoDetector: new (imageElement, width: number, height: number, mode) => Detector,
FaceDetectorMode: {
LARGE_FACES: 0,
SMALL_FACES: 1
};
};
type Detector = {
process: (imageElement: any, index: number) => void;
addEventListener: (eventName: string, data: any) => void;
detectAllEmotions();
detectAllExpressions();
start();
removeEventListener: (eventName: string, toRemove: Function) => void;
}
@legacyExtension()
@validGenericExtension()
export default class PoseFace extends Extension<Details, Blocks> {
/**
* The state the face's points, expressions, and emotions
*/
affdexState;
private affdexDetector: Detector;
/**
* The current video state
* @type {string}
*/
globalVideoState: string;
/**
* The current transparency of the video
* @type {number}
*/
globalVideoTransparency: number;
INTERVAL = 33;
DIMENSIONS = [480, 360];
expressions = info.menus.EXPRESSION.items
emotions = info.menus.EMOTION.items
all_emotions = info.menus.EMOTION_ALL.items
/**
* Acts like class PoseHand's constructor (instead of a child class constructor)
* @param env
*/
init(env: Environment) {
if (this.runtime.ioDevices) {
this.runtime.on(RuntimeEvent.ProjectStart, this.projectStarted.bind(this));
this._loop();
}
}
projectStarted() {
this.setTransparency(this.globalVideoTransparency);
this.toggleVideo(this.globalVideoState);
}
/**
* Converts the coordinates from the hand pose estimate to Scratch coordinates
* @param x
* @param y
* @returns enum
*/
convertCoordsToScratch({ x, y }) {
return { x: x - (this.DIMENSIONS[0] / 2), y: (this.DIMENSIONS[1] / 2) - y };
}
async _loop() {
while (true) {
const frame = this.runtime.ioDevices.video.getFrame({
format: 'image-data',
dimensions: this.DIMENSIONS
});
const time = +new Date();
if (frame) {
this.affdexState = await this.estimateAffdexOnImage(frame);
// TODO: Once indicators are implemented, indicate the state of the extension based on this.affdexState
}
const estimateThrottleTimeout = (+new Date() - time) / 4;
await new Promise(r => setTimeout(r, estimateThrottleTimeout));
}
}
async estimateAffdexOnImage(imageElement) {
const affdexDetector = await this.ensureAffdexLoaded(imageElement);
affdexDetector.process(imageElement, 0);
return new Promise((resolve, reject) => {
const resultListener = function (faces, image, timestamp) {
affdexDetector.removeEventListener("onImageResultsSuccess", resultListener);
if (faces.length < 1) {
resolve(null);
return;
}
resolve(faces[0]);
};
affdexDetector.addEventListener("onImageResultsSuccess", resultListener);
});
}
async ensureAffdexLoaded(imageElement) {
if (this.affdexDetector) return this.affdexDetector
const affdex: Affdex = await untilExternalGlobalVariableLoaded('https://download.affectiva.com/js/3.2.1/affdex.js', 'affdex');
const affdexStarter = new Promise((resolve, reject) => {
const width = this.DIMENSIONS[0];
const height = this.DIMENSIONS[1];
const faceMode = affdex.FaceDetectorMode.LARGE_FACES;
const detector = new affdex.PhotoDetector(imageElement, width, height, faceMode);
detector.detectAllEmotions();
detector.detectAllExpressions();
detector.start();
this.affdexDetector = detector;
detector.addEventListener("onInitializeSuccess", resolve);
});
await affdexStarter;
return this.affdexDetector;
}
/**
* Moves the target to a body part
* @param part
* @param util
* @returns None
*/
goToPart(part, util) {
if (!this.affdexState || !this.affdexState.featurePoints) return;
const featurePoint = this.affdexState.featurePoints[part];
const { x, y } = this.convertCoordsToScratch(featurePoint);
(util.target as any).setXY(x, y, false);
}
returnPart(coord, part, util) {
if (!this.affdexState || !this.affdexState.featurePoints) return;
const featurePoint = this.affdexState.featurePoints[part];
const { x, y } = this.convertCoordsToScratch(featurePoint);
if (coord === 'x') {
return x;
} else {
return y;
}
}
/**
* If an expression is being expressed
* @param expression
* @returns {boolean}
*/
isExpression(expression) {
if (!this.affdexState || !this.affdexState.expressions) {
return false;
}
return this.affdexState.expressions[expression] > .5;
}
/**
* How much of an expression is being expressed
* @param expression
* @returns {number}
*/
expressionAmount(expression) {
if (!this.affdexState || !this.affdexState.expressions) {
return 0;
}
return friendlyRound(this.affdexState.expressions[expression]);
}
/**
* Is an emotion is being expressed
* @param felt_emotion
* @param emotions
* @returns {boolean}
*/
isTopEmotion(felt_emotion, emotions) {
if (!this.affdexState || !this.affdexState.emotions) {
return false;
}
let maxEmotionValue = -Number.MAX_VALUE;
let maxEmotion = null;
emotions.forEach((emotion) => {
const emotionValue = this.affdexState.emotions[emotion.value];
if (emotionValue > maxEmotionValue) {
maxEmotionValue = emotionValue;
maxEmotion = emotion;
}
});
return felt_emotion == maxEmotion.value;
}
/**
* How much of an emotion is being expressed
* @param emotion
* @returns {number}
*/
emotionAmount(emotion) {
if (!this.affdexState || !this.affdexState.emotions) {
return 0;
}
return friendlyRound(this.affdexState.emotions[emotion]);
}
/**
* Turns the video camera off/on/on and flipped. This is called in the operation of videoToggleBlock
* @param state
*/
toggleVideo(state: string) {
if (state === VideoState.OFF) return this.runtime.ioDevices.video.disableVideo();
this.runtime.ioDevices.video.enableVideo();
// Mirror if state is ON. Do not mirror if state is ON_FLIPPED.
this.runtime.ioDevices.video.mirror = (state === VideoState.ON);
}
/**
* Sets the video's transparency. This is called in the operation of setVideoTransparencyBlock
* @param transparency
*/
setTransparency(transparency: number) {
const trans = Math.max(Math.min(transparency, 100), 0);
this.runtime.ioDevices.video.setPreviewGhost(trans);
}
/**
* Sets up the default settings for the extension. Gives information related to each of the extension's blocks
* @returns The extension's blocks
*/
defineBlocks(): PoseFace["BlockDefinitions"] {
/**
* Sets up the extension's default video settings
*/
this.globalVideoState = VideoState.ON;
this.globalVideoTransparency = 50;
this.projectStarted();
const handlerExpressions: Array<string> = this.expressions.map(expression => expression.value);
const handlerEmotionsShort: Array<string> = this.emotions.map(emotion => emotion.value);
const allEmotionValues: Array<string> = this.all_emotions.map(emotion => emotion.value);
const affdexGoToPart = legacyDefinition.affdexGoToPart({
operation: (part: string, util: BlockUtility) => {
this.goToPart(part, util)
}
});
const affdexReturnPart = legacyDefinition.affdexReturnPart({
operation: (coord: string, part: string, util: BlockUtility) => {
return this.returnPart(coord, part, util)
}
});
const affdexWhenExpression = legacyDefinition.affdexWhenExpression({
operation: (expression: string) => {
return this.isExpression(expression);
},
argumentMethods: {
0: {
handler: (expression: string) => {
return handlerExpressions.includes(expression) ? expression : 'smile';
}
}
}
});
const affdexExpressionAmount = legacyDefinition.affdexExpressionAmount({
operation: (expression: string) => {
return this.expressionAmount(expression);
},
argumentMethods: {
0: {
handler: (expression: string) => {
return handlerExpressions.includes(expression) ? expression : 'smile';
}
}
}
});
const affdexIsExpression = legacyDefinition.affdexIsExpression({
operation: (expression: string) => {
return this.isExpression(expression);
},
argumentMethods: {
0: {
handler: (expression: string) => {
return handlerExpressions.includes(expression) ? expression : 'smile';
}
}
}
});
const affdexWhenEmotion = legacyDefinition.affdexWhenEmotion({
operation: (emotion: string) => {
return this.isTopEmotion(emotion, this.emotions);
},
argumentMethods: {
0: {
handler: (emotion: string) => {
return handlerEmotionsShort.includes(emotion) ? emotion : 'joy';
}
}
}
});
const affdexEmotionAmount = legacyDefinition.affdexEmotionAmount({
operation: (emotion: string) => {
return this.emotionAmount(emotion)
},
argumentMethods: {
0: {
handler: (emotion: string) => {
return allEmotionValues.includes(emotion) ? emotion : 'joy';
}
}
}
});
const affdexIsTopEmotion = legacyDefinition.affdexIsTopEmotion({
operation: (emotion: string) => {
return this.isTopEmotion(emotion, this.emotions);
},
argumentMethods: {
0: {
handler: (emotion: string) => {
return handlerEmotionsShort.includes(emotion) ? emotion : 'joy';
}
}
}
});
// VIDEO BLOCKS
const videoToggle = legacyDefinition.videoToggle({
operation: (video_state) => {
this.toggleVideo(video_state);
},
argumentMethods: {
0: {
handler: (video_state: string) => {
return ['on', 'off', 'on-flipped'].includes(video_state) ? video_state : VideoState.ON;
},
}
}
});
const setVideoTransparency = legacyDefinition.setVideoTransparency({
operation: (transparency: number) => {
this.setTransparency(transparency);
}
});
return {
affdexGoToPart,
affdexReturnPart,
affdexWhenExpression,
affdexExpressionAmount,
affdexIsExpression,
affdexWhenEmotion,
affdexEmotionAmount,
affdexIsTopEmotion,
videoToggle,
setVideoTransparency
}
}
}