From 50962441f8296806151e6f4dafafae94efcfe897 Mon Sep 17 00:00:00 2001 From: Eric Anderson Date: Sun, 22 Nov 2026 13:48:20 -0800 Subject: [PATCH] Move the DOM-free simulator code into pxtsimcore - Split pxtsim into two projects sharing the pxsim namespace: pxtsimcore/ for the runtime, board state, sound and host layers, pxtsim/ for the embed, views, Web Audio and iframes. - pxtsimcore compiles without the dom lib, so core code that references the DOM fails the build. - Most of the diff is renames. The content changes are in embed.ts, simlib.ts, debugger.ts and runtime.ts, where the DOM-free parts were split out into new core files. - Kept built/pxtsim.js and built/pxtsim.d.ts as the outputs, so nothing changes for consumers. - Added pxtsimcore/README.md: the layout, the boundary rules, the host layers and the virtual host. - Made the gulp pxtsim task compile pxtsimcore, then pxtsim against its declarations, and concatenate the two. Added pxtsimcore to the lint, updatestrings and watch lists. Build and the simulator test tasks pass. --- .github/copilot-instructions.md | 2 +- .../instructions/simulator.instructions.md | 25 +- gulpfile.js | 21 +- pxtlib/browserutils.ts | 2 +- pxtlib/commonutil.ts | 2 +- pxtsim/debugger.ts | 190 ---------- pxtsim/domutils.ts | 61 +++ pxtsim/embed.ts | 343 ----------------- pxtsim/instructions.ts | 10 +- pxtsim/simlib.ts | 252 ------------ pxtsim/tsconfig.json | 4 +- pxtsim/visuals/boardhost.ts | 2 +- pxtsim/visuals/breadboard.ts | 6 - pxtsimcore/.eslintrc.js | 5 + pxtsimcore/README.md | 127 +++++++ {pxtsim => pxtsimcore}/allocator.ts | 7 +- {pxtsim => pxtsimcore}/debugProtocol.ts | 4 +- pxtsimcore/debugcore.ts | 188 +++++++++ pxtsimcore/eventbus.ts | 145 +++++++ pxtsimcore/globals.d.ts | 59 +++ {pxtsim => pxtsimcore}/host.ts | 0 {pxtsim => pxtsimcore}/langsupport.ts | 0 {pxtsim => pxtsimcore}/libgeneric.ts | 2 + {pxtsim => pxtsimcore}/localization.ts | 0 {pxtsim => pxtsimcore}/logger.ts | 0 pxtsimcore/messages.ts | 358 ++++++++++++++++++ {pxtsim => pxtsimcore}/runtime.ts | 60 --- {pxtsim => pxtsimcore}/sound/audiohost.ts | 0 {pxtsim => pxtsimcore}/sound/instructions.ts | 0 .../sound/musicalProgressions.ts | 0 {pxtsim => pxtsimcore}/sound/sequencer.ts | 0 {pxtsim => pxtsimcore}/sound/song.ts | 0 .../sound/soundEmojiSynthesizer.ts | 0 .../sound/soundSynthesizer.ts | 0 .../sound/soundSynthesizerEffects.ts | 0 .../sound/soundexpression.ts | 0 pxtsimcore/state/animationqueue.ts | 75 ++++ {pxtsim => pxtsimcore}/state/buttonpair.ts | 0 {pxtsim => pxtsimcore}/state/compass.ts | 0 {pxtsim => pxtsimcore}/state/filesystem.ts | 0 {pxtsim => pxtsimcore}/state/lightsensor.ts | 0 pxtsimcore/tsconfig.json | 21 + {pxtsim => pxtsimcore}/utils.ts | 0 {pxtsim => pxtsimcore}/virtualhost.ts | 0 pxtsimcore/visuals/boardgeometry.ts | 45 +++ 45 files changed, 1139 insertions(+), 877 deletions(-) create mode 100644 pxtsim/domutils.ts create mode 100644 pxtsimcore/.eslintrc.js create mode 100644 pxtsimcore/README.md rename {pxtsim => pxtsimcore}/allocator.ts (99%) rename {pxtsim => pxtsimcore}/debugProtocol.ts (99%) create mode 100644 pxtsimcore/debugcore.ts create mode 100644 pxtsimcore/eventbus.ts create mode 100644 pxtsimcore/globals.d.ts rename {pxtsim => pxtsimcore}/host.ts (100%) rename {pxtsim => pxtsimcore}/langsupport.ts (100%) rename {pxtsim => pxtsimcore}/libgeneric.ts (99%) rename {pxtsim => pxtsimcore}/localization.ts (100%) rename {pxtsim => pxtsimcore}/logger.ts (100%) create mode 100644 pxtsimcore/messages.ts rename {pxtsim => pxtsimcore}/runtime.ts (96%) rename {pxtsim => pxtsimcore}/sound/audiohost.ts (100%) rename {pxtsim => pxtsimcore}/sound/instructions.ts (100%) rename {pxtsim => pxtsimcore}/sound/musicalProgressions.ts (100%) rename {pxtsim => pxtsimcore}/sound/sequencer.ts (100%) rename {pxtsim => pxtsimcore}/sound/song.ts (100%) rename {pxtsim => pxtsimcore}/sound/soundEmojiSynthesizer.ts (100%) rename {pxtsim => pxtsimcore}/sound/soundSynthesizer.ts (100%) rename {pxtsim => pxtsimcore}/sound/soundSynthesizerEffects.ts (100%) rename {pxtsim => pxtsimcore}/sound/soundexpression.ts (100%) create mode 100644 pxtsimcore/state/animationqueue.ts rename {pxtsim => pxtsimcore}/state/buttonpair.ts (100%) rename {pxtsim => pxtsimcore}/state/compass.ts (100%) rename {pxtsim => pxtsimcore}/state/filesystem.ts (100%) rename {pxtsim => pxtsimcore}/state/lightsensor.ts (100%) create mode 100644 pxtsimcore/tsconfig.json rename {pxtsim => pxtsimcore}/utils.ts (100%) rename {pxtsim => pxtsimcore}/virtualhost.ts (100%) create mode 100644 pxtsimcore/visuals/boardgeometry.ts diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c4955dd62da6..6e996e062356 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -13,7 +13,7 @@ - The PXT framework follows a modular architecture with clear separation between: - Core framework (`pxtlib/`, `pxtcompiler/`) - Web application (`webapp/`) - - Simulator (`pxtsim/`) + - Simulator (`pxtsimcore/` DOM-free core, `pxtsim/` DOM and view code) - Target implementations (`pxt-microbit/`, `pxt-common-packages/`) ## Code Generation Standards diff --git a/.github/instructions/simulator.instructions.md b/.github/instructions/simulator.instructions.md index d50e57dd390d..157db6c2d5b1 100644 --- a/.github/instructions/simulator.instructions.md +++ b/.github/instructions/simulator.instructions.md @@ -1,6 +1,6 @@ --- description: "Instructions for PXT simulator development" -applyTo: "pxtsim/**/*.ts,sim/**/*.ts,**/sim/*.ts" +applyTo: "pxtsim/**/*.ts,pxtsimcore/**,sim/**/*.ts,**/sim/*.ts" --- # PXT Simulator Development Instructions @@ -11,10 +11,27 @@ applyTo: "pxtsim/**/*.ts,sim/**/*.ts,**/sim/*.ts" - Separate visual rendering from simulation logic - Use TypeScript interfaces to define board state contracts - Implement proper cleanup in simulation lifecycle methods +- `pxtsimcore` is the DOM-free core project; it compiles without the `dom` lib, which is the check +- New runtime, board-state and synthesis code belongs to `pxtsimcore`; only view code belongs to `pxtsim` +- Globals the core may use are declared in `pxtsimcore/globals.d.ts`; never add the `dom` lib to core +- Consumers load `built/pxtsim.js`, which is core followed by the DOM code; keep the `pxsim` namespace + +## Host Abstractions + +- Core reads time, timers and randomness through `host.clock()`, `host.timers()` and `host.rng()`, never `Date.now`, `setTimeout`, `setInterval`, `requestAnimationFrame` or `Math.random` +- Core talks to the parent page through `host.environment()` and plays sound through `audiohost.audio()` +- Core reports through `pxsim.log`, `pxsim.warn` and `pxsim.error` (the `pxsim.Logger` a host may replace), never `console` directly +- A new host interface defaults to today's behavior, and its setter takes only the members a caller wants to change, as `setEnvironment` does + +## Board State and View + +- `board()` is the state, used by shims and `state/*`; `boardView()` is for view code; state files never reference `visuals` +- A board state must construct and run with no view +- Tests inject input through the board state the same way the visuals do, not by raising DAL events by id ## Audio/Media Handling -- Use Web Audio API for audio processing and effects +- Web Audio lives in the `audiohost` DOM implementation; core code plays sound through `audiohost.audio()` - Implement proper gain control and volume management - Handle browser compatibility issues (Chrome, Firefox, Safari) - Use MediaStream API for recording functionality @@ -31,7 +48,7 @@ applyTo: "pxtsim/**/*.ts,sim/**/*.ts,**/sim/*.ts" ## Performance Optimization - Minimize DOM manipulations during animation -- Use requestAnimationFrame for smooth animations +- Use `requestAnimationFrame` for smooth animations in view code; core uses `host.timers().requestFrame` - Implement efficient update cycles - Cache frequently accessed DOM elements - Profile performance in different browsers @@ -39,7 +56,7 @@ applyTo: "pxtsim/**/*.ts,sim/**/*.ts,**/sim/*.ts" ## Hardware Simulation - Accurately model hardware behavior and constraints -- Implement realistic timing and delays +- Implement realistic timing and delays on the host clock - Handle edge cases and error conditions - Support debugging and breakpoint functionality - Maintain compatibility with runtime implementations diff --git a/gulpfile.js b/gulpfile.js index 318bce678253..062987f2689a 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -100,7 +100,20 @@ const copyTypescriptServices = () => gulp.src("pxtcompiler/ext-typescript/lib/ty const pxtlib = () => compileTsProject("pxtlib"); const pxtcompiler = () => compileTsProject("pxtcompiler"); const pxtpy = () => compileTsProject("pxtpy"); -const pxtsim = () => compileTsProject("pxtsim"); +const pxtsimDom = () => compileTsProject("pxtsim", "built", false, "pxtsimdom"); +const compilePxtsimcore = () => compileTsProject("pxtsimcore"); +const copyPxtsimcoreGlobals = () => gulp.src("pxtsimcore/globals.d.ts") + .pipe(concat("pxtsimcore-globals.d.ts")) + .pipe(gulp.dest("built")); +const pxtsimcore = gulp.parallel(compilePxtsimcore, copyPxtsimcoreGlobals); +const combinePxtsim = () => gulp.src(["built/pxtsimcore.js", "built/pxtsimdom.js"]) + .pipe(concat("pxtsim.js")) + .pipe(gulp.dest("built")); +const combinePxtsimDeclarations = () => gulp.src(["built/pxtsimcore.d.ts", "built/pxtsimdom.d.ts"]) + .pipe(concat("pxtsim.d.ts")) + .pipe(replace(/^\/\/\/ [ \t]*\r?\n/gm, "")) + .pipe(gulp.dest("built")); +const pxtsim = gulp.series(pxtsimcore, pxtsimDom, gulp.parallel(combinePxtsim, combinePxtsimDeclarations)); const pxtrunner = () => compileTsProject("pxtrunner", "built", true); const pxteditor = () => compileTsProject("pxteditor", "built", true); const pxtweb = () => compileTsProject("docfiles/pxtweb", "built/web"); @@ -219,6 +232,7 @@ function initWatch() { gulp.watch("./pxtcompiler/**/*", gulp.series(pxtcompiler, ...tasks.slice(2))); gulp.watch("./pxtsim/**/*", gulp.series(pxtsim, ...tasks.slice(2))); + gulp.watch("./pxtsimcore/**/*", gulp.series(pxtsim, ...tasks.slice(2))); gulp.watch("./backendutils/**/*", gulp.series(backendutils, ...tasks.slice(2))); gulp.watch("./pxtpy/**/*", gulp.series(pxtpy, ...tasks.slice(3))); @@ -323,6 +337,7 @@ function updatestrings() { "pxtlib", "pxtpy", "pxtsim", + "pxtsimcore", "webapp/src", "react-common" ], true); @@ -742,7 +757,7 @@ const maybeBuildWebapps = () => { const lintWithEslint = () => Promise.all( ["cli", "pxtblocks", "pxteditor", "pxtlib", "pxtcompiler", - "pxtpy", "pxtrunner", "pxtsim", "webapp", "pxtservices", + "pxtpy", "pxtrunner", "pxtsim", "pxtsimcore", "webapp", "pxtservices", "docfiles/pxtweb", "skillmap", "authcode", "multiplayer"/*, "kiosk"*/, "teachertool", "docs/static/streamer"].map(dirname => exec(`node node_modules/eslint/bin/eslint.js -c .eslintrc.js --ext .ts,.tsx ./${dirname}/`, true))) @@ -957,6 +972,8 @@ exports.testpxteditor = testpxteditor; exports.testprojecttools = testprojecttools; exports.testcli = testcli; exports.reactCommon = reactCommon; +exports.pxtsimcore = pxtsimcore; +exports.pxtsim = pxtsim; exports.cli = gulp.series( gulp.parallel(pxtlib, pxtweb), gulp.parallel(pxtcompiler, pxtsim, backendutils), diff --git a/pxtlib/browserutils.ts b/pxtlib/browserutils.ts index 58f81b2a0db1..52ae3e510664 100644 --- a/pxtlib/browserutils.ts +++ b/pxtlib/browserutils.ts @@ -1365,7 +1365,7 @@ namespace pxt.BrowserUtils { } } - // Keep these helpers unified with pxtsim/runtime.ts + // Keep these helpers unified with pxtsim/domutils.ts export function containsClass(el: SVGElement | HTMLElement, classes: string) { return splitClasses(classes).every(cls => containsSingleClass(el, cls)); diff --git a/pxtlib/commonutil.ts b/pxtlib/commonutil.ts index 0e8d5ffa0f6a..7521f6ef55c9 100644 --- a/pxtlib/commonutil.ts +++ b/pxtlib/commonutil.ts @@ -68,7 +68,7 @@ namespace ts.pxtc.Util { } } - // Localization functions. Please port any modifications over to pxtsim/localization.ts + // Localization functions. Please port any modifications over to pxtsimcore/localization.ts let _localizeLang: string = "en"; let _localizeStrings: pxt.Map = {}; let _translationsCache: pxt.Map> = {}; diff --git a/pxtsim/debugger.ts b/pxtsim/debugger.ts index f512cf023030..ff51b0654119 100644 --- a/pxtsim/debugger.ts +++ b/pxtsim/debugger.ts @@ -1,24 +1,4 @@ -/// -/// - namespace pxsim { - export function getWarningMessage(msg: string) { - let r: DebuggerWarningMessage = { - type: "debugger", - subtype: "warning", - breakpointIds: [], - message: msg - } - - let s = runtime.currFrame - while (s != null) { - r.breakpointIds.push(s.lastBrkId) - s = s.parent - } - - return r - } - export class BreakpointMap { public fileMap: { [index: string]: [number, DebugProtocol.Breakpoint][] } = {}; public idMap: { [index: number]: DebugProtocol.Breakpoint } = {}; @@ -83,176 +63,6 @@ namespace pxsim { } } - function valToJSON(v: any, heap: Map) { - switch (typeof v) { - case "string": - case "number": - case "boolean": - return v; - case "function": - return { - text: "(function)", - type: "function", - } - case "undefined": - return null; - case "object": - if (!v) return null; - if (v instanceof RefObject) { - if (heap) heap[(v as RefObject).id] = v; - let preview = RefObject.toDebugString(v); - let type = preview.startsWith('[') ? "array" : preview; - return { - id: (v as RefObject).id, - preview: preview, - hasFields: (v as any).fields !== null || preview.startsWith('['), - type: type, - } - } - if (v._width && v._height) { - return { - text: v._width + 'x' + v._height, - type: "image", - } - } - return { - text: "(object)", - type: "object", - } - default: - throw new Error(); - } - } - - export function dumpHeap(v: any, heap: Map, fields?: string[], filters?: string[], includeAll = false): Variables { - function frameVars(frame: any, fields?: string[]) { - const r: Variables = {} - for (let k of Object.keys(frame)) { - // skip members starting with __ - if (!/^__/.test(k) && /___\d+$/.test(k) && (!filters || filters.indexOf(k) !== -1)) { - r[k] = valToJSON(frame[k], heap) - } - } - if (frame.fields && fields) { - // Fields of an object. - for (let k of fields) { - k = k.substring(k.lastIndexOf(".") + 1); - r[k] = valToJSON(evalGetter(frame.vtable.iface[k], frame), heap); - } - } - if (frame.fields) { - for (let k of Object.keys(frame.fields).filter(field => includeAll || !field.startsWith('_'))) { - r[k] = valToJSON(frame.fields[k], heap) - } - } - else if (frame instanceof RefMap) { - for (const entry of frame.data) { - r[entry.key] = valToJSON(entry.val, heap); - } - } - else if (Array.isArray(frame.data)) { - // This is an Array. - (frame.data as any[]).forEach((element, index) => { - r[index] = valToJSON(element, heap); - }); - } - else if (frame._width !== undefined && frame._height !== undefined) { - // Probably a RefImage - r["width"] = frame._width; - r["height"] = frame._height; - - if (includeAll && frame._bpp !== undefined) { - r["isMono"] = frame._bpp === 1; - } - } - return r - } - - return frameVars(v, fields); - } - - function evalGetter(fn: LabelFn, target: RefObject) { - // This function evaluates a getter, and we assume it doesn't have any side effects. - let parentFrame: any = { - }; - - // We create a dummy stack frame - let stackFrame: any = { - pc: 0, - arg0: target, - fn, - parent: parentFrame - }; - - // And we evaluate the getter - while (stackFrame.fn) { - stackFrame = stackFrame.fn(stackFrame as any); - } - - return stackFrame.retval; - } - - export function injectEnvironmentGlobals(msg: DebuggerBreakpointMessage, heap: Map) { - const environmentGlobals = runtime.environmentGlobals; - const keys = Object.keys(environmentGlobals); - if (!keys.length) - return; - - const envVars: Variables = msg.environmentGlobals = {}; - Object.keys(environmentGlobals) - .forEach(n => envVars[n] = valToJSON(runtime.environmentGlobals[n], heap)) - } - - export function getBreakpointMsg(s: pxsim.StackFrame, brkId: number, userGlobals?: string[]): { msg: DebuggerBreakpointMessage, heap: Map } { - const heap: pxsim.Map = {}; - - const msg: DebuggerBreakpointMessage = { - type: "debugger", - subtype: "breakpoint", - breakpointId: brkId, - globals: dumpHeap(runtime.globals, heap, undefined, userGlobals), - stackframes: [], - } - - while (s != null) { - let info = getInfoForFrame(s, heap); - if (info) - msg.stackframes.push(info) - s = s.parent - } - - return { msg, heap }; - } - - function getInfoForFrame(s: pxsim.StackFrame, heap: any): StackFrameInfo { - let info = s.fn ? (s.fn as any).info : null - if (info) { - let argInfo: FunctionArgumentsInfo = { - thisParam: valToJSON((s as any).argL, heap), - params: [] - }; - - if (info.argumentNames) { - const args = info.argumentNames as string[]; - argInfo.params = args.map((paramName, index) => ({ - name: paramName, - value: valToJSON((s as any)["arg" + index], heap) - })); - } - - return { - locals: dumpHeap(s, heap), - funcInfo: info, - breakpointId: s.lastBrkId, - callLocationId: s.callLocIdx, - arguments: argInfo - }; - } - - return undefined; - } - - export interface SimLaunchArgs extends DebugProtocol.LaunchRequestArguments { /* Root directory of the project workspace being debugged */ projectDir: string; diff --git a/pxtsim/domutils.ts b/pxtsim/domutils.ts new file mode 100644 index 000000000000..4b0596fbb602 --- /dev/null +++ b/pxtsim/domutils.ts @@ -0,0 +1,61 @@ +namespace pxsim.U { + // Keep these helpers unified with pxtlib/browserutils.ts + export function containsClass(el: SVGElement | HTMLElement, classes: string) { + return splitClasses(classes).every(cls => containsSingleClass(el, cls)); + + function containsSingleClass(el: SVGElement | HTMLElement, cls: string) { + if (el.classList) { + return el.classList.contains(cls); + } else { + const classes = (el.className + "").split(/\s+/); + return !(classes.indexOf(cls) < 0); + } + } + } + + export function addClass(el: SVGElement | HTMLElement, classes: string) { + splitClasses(classes).forEach(cls => addSingleClass(el, cls)); + + function addSingleClass(el: SVGElement | HTMLElement, cls: string) { + if (el.classList) { + el.classList.add(cls); + } else { + const classes = (el.className + "").split(/\s+/); + if (classes.indexOf(cls) < 0) { + el.className.baseVal += " " + cls; + } + } + } + } + + export function removeClass(el: SVGElement | HTMLElement, classes: string) { + splitClasses(classes).forEach(cls => removeSingleClass(el, cls)); + + function removeSingleClass(el: SVGElement | HTMLElement, cls: string) { + if (el.classList) { + el.classList.remove(cls); + } else { + el.className.baseVal = (el.className + "") + .split(/\s+/) + .filter(c => c != cls) + .join(" "); + } + } + } + + function splitClasses(classes: string) { + return classes.split(/\s+/).filter(s => !!s); + } + + export function remove(element: Element) { + element.parentElement.removeChild(element); + } + + export function removeChildren(element: Element) { + while (element.firstChild) element.removeChild(element.firstChild); + } + + export function clear(element: Element) { + removeChildren(element); + } +} diff --git a/pxtsim/embed.ts b/pxtsim/embed.ts index 777e74c30232..aa8113f33602 100644 --- a/pxtsim/embed.ts +++ b/pxtsim/embed.ts @@ -2,349 +2,6 @@ /// namespace pxsim { - export interface SimulatorRunMessage extends SimulatorMessage { - type: "run"; - id?: string; - boardDefinition?: BoardDefinition; - frameCounter?: number; - refCountingDebug?: boolean; - options?: any; - parts?: string[]; - builtinParts?: string[]; - partDefinitions?: Map - fnArgs?: any; - code: string; - mute?: boolean; - highContrast?: boolean; - light?: boolean; - cdnUrl?: string; - localizedStrings?: Map; - version?: string; - clickTrigger?: boolean; - breakOnStart?: boolean; - storedState?: Map; - ipc?: boolean; - dependencies?: Map; - single?: boolean; - traceDisabled?: boolean; - activePlayer?: 1 | 2 | 3 | 4 | undefined; - theme?: string | pxt.Map; - yieldDelay?: number; - } - - export interface SimulatorInstructionsMessage extends SimulatorMessage { - type: "instructions"; - options: pxsim.instructions.RenderPartsOptions; - } - - export interface SimulatorMuteMessage extends SimulatorMessage { - type: "mute"; - mute: boolean; - } - - export interface SimulatorStopSoundMessage extends SimulatorMessage { - type: "stopsound"; - } - - export interface SimulatorDocMessage extends SimulatorMessage { - type: "localtoken" | "docfailed"; - docType?: string; - src?: string; - localToken?: string; - } - - export interface SimulatorFileLoadedMessage extends SimulatorMessage { - type: "fileloaded"; - name: string; - // localeInfo NOT userLanguage - locale: string; - content?: string; - } - - export interface SimulatorReadyMessage extends SimulatorMessage { - type: "ready"; - frameid: string; - } - - export interface SimulatorTopLevelCodeFinishedMessage extends SimulatorMessage { - type: "toplevelcodefinished"; - } - - export interface SimulatorOpenDocMessage extends SimulatorMessage { - type: "opendoc"; - url: string; - } - - export type GlobalAction = "escape" | "toggleareamenu" | "togglekeyboardcontrolshelp"; - - export interface SimulatorActionMessage extends SimulatorMessage { - type: "action"; - action: GlobalAction; - } - - export interface SimulatorStateMessage extends SimulatorMessage { - type: "status"; - frameid?: string; - runtimeid?: string; - state: string; - } - export interface SimulatorBroadcastMessage extends SimulatorMessage { - broadcast: boolean; - toParentIFrameOnly?: boolean; - srcFrameIndex?: number; - } - - export interface SimulatorControlMessage extends SimulatorBroadcastMessage { - type: "messagepacket"; - channel: string; - data: Uint8Array; - } - - export interface SimulatorEventBusMessage extends SimulatorBroadcastMessage { - type: "eventbus"; - broadcast: true; - id: number; - eventid: number; - value?: number; - } - export interface SimulatorSerialMessage extends SimulatorMessage { - type: "serial"; - id: string; - data: string; - sim?: boolean; - csvType?: undefined | "headers" | "row" | "clear"; // if non-nullish pass to csv view instead - receivedTime?: number; - } - export interface SimulatorBulkSerialMessage extends SimulatorMessage { - type: "bulkserial"; - id: string; - data: { data: string, time: number }[]; - sim?: boolean; - } - export interface SimulatorCommandMessage extends SimulatorMessage { - type: "simulator", - command: "modal" | "restart" | "reload" | "setstate" | "focus" | "blur" | "single" - stateKey?: string; - stateValue?: any; - header?: string; - body?: string; - copyable?: string; - linkButtonHref?: string; - linkButtonLabel?: string; - displayOnceId?: string; // An id for the modal command, if the sim wants the modal to be displayed only once in the session - modalContext?: string; // Modal context of where to show the modal - timestamp?: number; - } - export interface SimulatorRadioPacketMessage extends SimulatorBroadcastMessage { - type: "radiopacket"; - broadcast: true; - rssi: number; - serial: number; - time: number; - - payload: SimulatorRadioPacketPayload; - } - export interface SimulatorInfraredPacketMessage extends SimulatorBroadcastMessage { - type: "irpacket"; - broadcast: true; - packet: Uint8Array; // base64 encoded - } - export interface SimulatorBLEPacketMessage extends SimulatorBroadcastMessage { - type: "blepacket"; - broadcast: true; - packet: Uint8Array; - } - export interface SimulatorI2CMessage extends SimulatorMessage { - type: "i2c"; - data: Uint8Array; - } - - export interface SimulatorRadioPacketPayload { - type: number; - groupId: number; - stringData?: string; - numberData?: number; - } - - export interface SimulatorCustomMessage extends SimulatorMessage { - type: "custom"; - content: any; - } - - export interface SimulatorScreenshotMessage extends SimulatorMessage { - type: "screenshot"; - data: ImageData; - delay?: number; - modalContext?: string; - } - - export interface SimulatorAutomaticThumbnailMessage extends SimulatorMessage { - type: "thumbnail"; - frames: ImageData[]; - } - - export interface SimulatorAddExtensionsMessage extends SimulatorMessage { - type: "addextensions", - /** - * List of repositories to add - */ - extensions: string[] - } - - export interface SimulatorAspectRatioMessage extends SimulatorMessage { - type: "aspectratio", - value: number, - frameid: string - } - - export interface SimulatorRecorderMessage extends SimulatorMessage { - type: "recorder"; - action: "start" | "stop"; - width?: number; - } - - export interface TutorialMessage extends SimulatorMessage { - type: "tutorial"; - tutorial: string; - subtype: string; - } - - export interface ImportFileMessage extends SimulatorMessage { - type: "importfile"; - filename: string; - parts: (string | ArrayBuffer)[]; - } - - export interface TutorialStepInfo { - fullscreen?: boolean; - contentMd?: string; - headerContentMd?: string; - hintContentMd?: string; - } - - export interface TutorialLoadedMessage extends TutorialMessage { - subtype: "loaded"; - showCategories?: boolean; - stepInfo: TutorialStepInfo[]; - toolboxSubset?: { [index: string]: number }; - } - - export interface TutorialStepChangeMessage extends TutorialMessage { - subtype: "stepchange"; - step: number; - } - - export interface TutorialFailedMessage extends TutorialMessage { - subtype: "error"; - message?: string; - } - - export interface RenderReadyResponseMessage extends SimulatorMessage { - source: "makecode", - type: "renderready", - versions: pxt.TargetVersions - } - - export interface RenderBlocksRequestMessage extends SimulatorMessage { - type: "renderblocks", - id: string; - code?: string; - options?: { - packageId?: string; - package?: string; - snippetMode?: boolean; - // only send back the svg: no png and no data uri (uri stays undefined) - svgOnly?: boolean; - } - } - - export interface RenderBlocksResponseMessage extends SimulatorMessage { - source: "makecode", - type: "renderblocks", - id: string; - svg?: string; - width?: number; - height?: number; - css?: string; - uri?: string; - error?: string; - } - - export interface SetActivePlayerMessage extends SimulatorMessage { - type: "setactiveplayer"; - playerNumber: 1 | 2 | 3 | 4 | undefined; - } - - export interface SetSimThemeMessage extends SimulatorMessage { - type: "setsimthemecolor"; - part: string; - color: string; - } - - export interface SetSimulatorThemeMessage extends SimulatorMessage { - type: "setsimtheme"; - theme: string | pxt.Map; - } - - export interface SetMuteButtonStateMessage extends SimulatorMessage { - type: "setmutebuttonstate"; - state: "muted" | "unmuted" | "disabled"; - } - - export namespace multiplayer { - type MessageBase = { - type: "multiplayer"; - origin?: "server" | "client"; - broadcast?: boolean; - }; - - export enum IconType { - Player = 0, - Reaction = 1, - } - - export type ImageMessage = MessageBase & { - content: "Image"; - image?: pxsim.RefBuffer; // pxsim.RefBuffer - palette: Uint8Array; - }; - - export type InputMessage = MessageBase & { - content: "Button"; - button: number; - clientNumber: number; - state: "Pressed" | "Released" | "Held"; - }; - - export type AudioMessage = MessageBase & { - content: "Audio"; - instruction: audiohost.SoundEvent; - soundbuf?: Uint8Array; - }; - - export type IconMessage = MessageBase & { - content: "Icon"; - icon?: pxsim.RefBuffer; // pxsim.RefBuffer - slot: number; - iconType: IconType; - // 48bytes, [r0,g0,b0,r1,g1,b1,...] - palette: Uint8Array; - }; - - export type ConnectionMessage = MessageBase & { - content: "Connection"; - slot: number; - connected: boolean; - } - - export type Message = - | ImageMessage - | AudioMessage - | InputMessage - | IconMessage - | ConnectionMessage; - } - export function print(delay: number = 0) { function p() { try { diff --git a/pxtsim/instructions.ts b/pxtsim/instructions.ts index ef4738070ce3..9273ae7ef212 100644 --- a/pxtsim/instructions.ts +++ b/pxtsim/instructions.ts @@ -554,15 +554,7 @@ namespace pxsim.instructions { return [panel, props]; } - export interface RenderPartsOptions { - name: string; - boardDef: BoardDefinition; - parts: string[]; - partDefinitions: Map; - fnArgs: any; - configData: pxsim.ConfigData; - print?: boolean; - } + export type RenderPartsOptions = SimulatorInstructionsOptions; export function renderParts(container: HTMLElement, options: RenderPartsOptions) { if (!options.boardDef.pinStyles) diff --git a/pxtsim/simlib.ts b/pxtsim/simlib.ts index 0f194e477e4a..f585ef51f64c 100644 --- a/pxtsim/simlib.ts +++ b/pxtsim/simlib.ts @@ -1,222 +1,4 @@ namespace pxsim { - export type BoardPin = string; - export interface BBLoc { - type: "breadboard", - row: string, - col: string - xOffset?: number, - yOffset?: number, - style?: PinStyle; - }; - export interface BoardLoc { - type: "dalboard", - pin: BoardPin - }; - export type Loc = BBLoc | BoardLoc; - - export function mkRange(a: number, b: number): number[] { - let res: number[] = []; - for (; a < b; a++) - res.push(a); - return res; - } - - export class EventBus { - private queues: Map = {}; - private notifyID: number; - private notifyOneID: number; - private schedulerID: number; - private idleEventID: number; - private lastEventValue: string | number; - private lastEventTimestampUs: number; - private backgroundHandlerFlag: boolean = false; - - public nextNotifyEvent = 1024; - - constructor( - private readonly runtime: Runtime, - private readonly board: BaseBoard, - private readonly valueToArgs?: EventValueToActionArgs - ) { - this.schedulerID = 15; // DEVICE_ID_SCHEDULER - this.idleEventID = 2; // DEVICE_SCHEDULER_EVT_IDLE - - this.board.addMessageListener(this.handleMessage.bind(this)); - } - - private handleMessage(msg: pxsim.SimulatorMessage) { - if (msg.type === "eventbus") { - const ev = msg; - this.queue(ev.id, ev.eventid, ev.value); - } - } - - public setBackgroundHandlerFlag() { - this.backgroundHandlerFlag = true; - } - - public setNotify(notifyID: number, notifyOneID: number) { - this.notifyID = notifyID; - this.notifyOneID = notifyOneID; - } - - public setIdle(schedulerID: number, idleEventID: number) { - this.schedulerID = schedulerID; - this.idleEventID = idleEventID; - } - - private start(id: EventIDType, evid: EventIDType, background: boolean, create: boolean = false) { - let key = (background ? "back" : "fore") + ":" + id + ":" + evid - if (!this.queues[key] && create) this.queues[key] = new EventQueue(this.runtime, this.valueToArgs); - return this.queues[key]; - } - - listen(id: EventIDType, evid: EventIDType, handler: RefAction, flags = 0) { - // special handle for idle, start the idle timeout - if (id == this.schedulerID && evid == this.idleEventID) - this.runtime.startIdle(); - - let q = this.start(id, evid, this.backgroundHandlerFlag, true); - if (this.backgroundHandlerFlag) { - q.addHandler(handler, flags); - } - else { - q.setHandler(handler, flags); - } - this.backgroundHandlerFlag = false; - } - - removeBackgroundHandler(handler: RefAction) { - Object.keys(this.queues).forEach((k: string) => { - if (k.startsWith("back:")) - this.queues[k].removeHandler(handler) - }); - } - - // this handles ANY (0) semantics for id and evid - private getQueues(id: EventIDType, evid: EventIDType, bg: boolean) { - let ret = [this.start(0, 0, bg)] - if (id == 0 && evid == 0) - return ret - if (evid) - ret.push(this.start(0, evid, bg)) - if (id) - ret.push(this.start(id, 0, bg)) - if (id && evid) - ret.push(this.start(id, evid, bg)) - return ret - } - - queue(id: EventIDType, evid: EventIDType, value: EventIDType = null) { - if (runtime.pausedOnBreakpoint) return; - // special handling for notify one - const notifyOne = this.notifyID && this.notifyOneID && id == this.notifyOneID; - if (notifyOne) - id = this.notifyID; - let queues = this.getQueues(id, evid, true).concat(this.getQueues(id, evid, false)) - this.lastEventValue = evid; - this.lastEventTimestampUs = U.perfNowUs(); - - U.promiseMapAllSeries(queues, q => { - if (q) return q.push(value, notifyOne); - else return Promise.resolve() - }) - } - - queueIdle() { - if (this.schedulerID && this.idleEventID) - this.queue(this.schedulerID, this.idleEventID); - } - - // only for foreground handlers - wait(id: number | string, evid: number | string, cb: (value?: any) => void) { - let q = this.start(id, evid, false, true); - q.addAwaiter(cb); - } - - getLastEventValue() { - return this.lastEventValue; - } - - getLastEventTime() { - return 0xffffffff & (this.lastEventTimestampUs - runtime.startTimeUs); - } - } - - export interface AnimationOptions { - interval: number; - // false means last frame - frame: () => boolean; - whenDone?: (cancelled: boolean) => void; - setTimeoutHandle?: host.TimerHandle; - } - - export class AnimationQueue { - private queue: AnimationOptions[] = []; - private process: () => void; - - constructor(private runtime: Runtime) { - this.process = () => { - let top = this.queue[0]; - if (!top) return; - if (this.runtime.dead) return; - runtime = this.runtime; - let res = top.frame(); - runtime.queueDisplayUpdate(); - runtime.maybeUpdateDisplay(); - if (res === false) { - this.queue.shift(); - // if there is already something in the queue, start processing - if (this.queue[0]) { - this.queue[0].setTimeoutHandle = host.timers().setTimeout(this.process, this.queue[0].interval); - } - // this may push additional stuff - top.whenDone(false); - } else { - top.setTimeoutHandle = host.timers().setTimeout(this.process, top.interval); - } - } - } - - public cancelAll() { - let q = this.queue - this.queue = [] - for (let a of q) { - a.whenDone(true) - if (a.setTimeoutHandle) { - host.timers().clearTimeout(a.setTimeoutHandle); - } - } - } - - public cancelCurrent() { - let top = this.queue[0] - if (top) { - this.queue.shift(); - top.whenDone(true); - if (top.setTimeoutHandle) { - host.timers().clearTimeout(top.setTimeoutHandle); - } - } - } - - public enqueue(anim: AnimationOptions) { - if (!anim.whenDone) anim.whenDone = () => { }; - this.queue.push(anim) - // we start processing when the queue goes from 0 to 1 - if (this.queue.length == 1) - this.process() - } - - public executeAsync(anim: AnimationOptions) { - U.assert(!anim.whenDone) - return new Promise((resolve, reject) => { - anim.whenDone = resolve - this.enqueue(anim) - }) - } - } - export interface IPointerEvents { up: string, down: string[], @@ -378,20 +160,6 @@ namespace pxsim.visuals { return { el: img, w: w, h: h, x: 0, y: 0 }; } - export type Coord = [number, number]; - export function findDistSqrd(a: Coord, b: Coord): number { - let x = a[0] - b[0]; - let y = a[1] - b[1]; - return x * x + y * y; - } - export function findClosestCoordIdx(a: Coord, bs: Coord[]): number { - let dists = bs.map(b => findDistSqrd(a, b)); - let minIdx = dists.reduce((prevIdx, currDist, currIdx, arr) => { - return currDist < arr[prevIdx] ? currIdx : prevIdx; - }, 0); - return minIdx; - } - export function mkTxt(cx: number, cy: number, size: number, rot: number, txt: string, txtXOffFactor?: number, txtYOffFactor?: number): SVGTextElement { let el = svg.elt("text") //HACK: these constants (txtXOffFactor, txtYOffFactor) tweak the way this algorithm knows how to center the text @@ -408,26 +176,6 @@ namespace pxsim.visuals { return el; } - export type WireColor = - "black" | "white" | "gray" | "purple" | "blue" | "green" | "yellow" | "orange" | "red" | "brown" | "pink"; - export const GPIO_WIRE_COLORS = ["pink", "orange", "yellow", "green", "purple"]; - export const WIRE_COLOR_MAP: Map = { - black: "#514f4d", - white: "#fcfdfc", - gray: "#acabab", - purple: "#a772a1", - blue: "#01a6e8", - green: "#3cce73", - yellow: "#ece600", - orange: "#fdb262", - red: "#f44f43", - brown: "#c89764", - pink: "#ff80fa" - } - export function mapWireColor(clr: WireColor | string): string { - return WIRE_COLOR_MAP[clr] || clr; - } - export interface SVGAndSize { el: T, y: number, diff --git a/pxtsim/tsconfig.json b/pxtsim/tsconfig.json index bca881fa3f79..d0821aaac9a6 100644 --- a/pxtsim/tsconfig.json +++ b/pxtsim/tsconfig.json @@ -5,7 +5,7 @@ "noImplicitReturns": true, "noImplicitThis": true, "declaration": true, - "outFile": "../built/pxtsim.js", + "outFile": "../built/pxtsimdom.js", "newLine": "LF", "sourceMap": false, "moduleResolution": "node", @@ -20,7 +20,7 @@ "skipLibCheck": true }, "files": [ - "host.ts" + "../built/pxtsimcore.d.ts" ], "include": [ "**/*.ts" diff --git a/pxtsim/visuals/boardhost.ts b/pxtsim/visuals/boardhost.ts index 2b94a70dd6b7..c1f11b4dda88 100644 --- a/pxtsim/visuals/boardhost.ts +++ b/pxtsim/visuals/boardhost.ts @@ -287,7 +287,7 @@ namespace pxsim.visuals { return this.wireFactory.addWire(inst.start, inst.end, inst.color); } - public addAll(allocRes: AllocatorResult) { + public addAll(allocRes: AllocatorResult, Wire>) { allocRes.partsAndWires.forEach(pAndWs => { const wires = pAndWs.wires; const wiresOk = wires && wires.every(w => this.wireFactory.checkWire(w.start, w.end)); diff --git a/pxtsim/visuals/breadboard.ts b/pxtsim/visuals/breadboard.ts index f4c2e894b911..c7db2d853e4f 100644 --- a/pxtsim/visuals/breadboard.ts +++ b/pxtsim/visuals/breadboard.ts @@ -121,8 +121,6 @@ namespace pxsim.visuals { } ` // Pin rows and coluns - export const BREADBOARD_MID_ROWS = 10; - export const BREADBOARD_MID_COLS = 30; const MID_ROW_GAPS = [4, 4]; const MID_ROW_AND_GAPS = BREADBOARD_MID_ROWS + MID_ROW_GAPS.length; const BAR_ROWS = 2; @@ -166,10 +164,6 @@ namespace pxsim.visuals { const SMALL_CHANNEL_HEIGHT = PIN_DIST * 0.05; // Background const BACKGROUND_ROUNDING = PIN_DIST * 0.3; - // Row and column helpers - const alphabet = "abcdefghij".split("").reverse(); - export function getColumnName(colIdx: number): string { return `${colIdx + 1}` }; - export function getRowName(rowIdx: number): string { return alphabet[rowIdx] }; export interface GridPin { el: SVGElement, diff --git a/pxtsimcore/.eslintrc.js b/pxtsimcore/.eslintrc.js new file mode 100644 index 000000000000..30f6890d349e --- /dev/null +++ b/pxtsimcore/.eslintrc.js @@ -0,0 +1,5 @@ +module.exports = { + "parserOptions": { + "project": "pxtsimcore/tsconfig.json", + }, +} \ No newline at end of file diff --git a/pxtsimcore/README.md b/pxtsimcore/README.md new file mode 100644 index 000000000000..ca83fec66617 --- /dev/null +++ b/pxtsimcore/README.md @@ -0,0 +1,127 @@ +# The DOM-free simulator core + +The simulator is two TypeScript projects in one `pxsim` namespace. + +- `pxtsimcore/` is the runtime, board state, sound and host layers. It compiles without the `dom` + lib, so a core file that uses `document` or `window` fails to build. +- `pxtsim/` is the embed, SVG views, Web Audio and iframes. It compiles against `pxtsimcore.d.ts`. + +Consumers still load one `built/pxtsim.js`: core first, then the DOM code. + +## Layout + +A file belongs to the project whose directory contains it. + +``` +pxtsimcore/runtime.ts the VM, Runtime and the board base classes +pxtsimcore/host.ts, virtualhost.ts the host layer and its virtual implementation +pxtsimcore/sound/audiohost.ts the audio host layer +pxtsim/embed.ts receives editor messages and starts each run +pxtsim/domhost.ts, sound/audiohostdom.ts install the browser hosts +pxtsim/simdriver.ts SimulatorDriver, which the editor uses to run simulators +pxtsim/visuals/ BoardHost, the breadboard, generic parts and wiring +``` + +The gulp `pxtsim` task compiles core to `built/pxtsimcore.js`, compiles the DOM project against it, +and concatenates the two into `built/pxtsim.js` and `built/pxtsim.d.ts`. It also copies +`globals.d.ts` to `built/pxtsimcore-globals.d.ts`; a target's DOM-free code compiles against +`pxtsimcore.d.ts` and that file. All of these ship in pxt-core. + +## The boundary + +Core sees its own declarations, `pxtsimcore/globals.d.ts` and the `localtypings/` files it +references, and nothing from `pxtsim/`. `globals.d.ts` declares by hand what browsers, workers and +Node all have. A global that only some hosts have is typed as possibly undefined, so core checks +before calling it: + +```ts +requestFrame: fn => typeof requestAnimationFrame !== "undefined" + ? requestAnimationFrame(fn) : setTimeout(fn, FRAME_MS), +``` + +Time, timers and random numbers come from `pxsim.host`, and sound goes through `pxsim.audiohost`. +The one exception is the serial timestamp, which stays on `Date.now()` because the serial view +shows wall-clock time. + +Each project compiles to one script, so a file used by another at load time must come first. A +reference pins the order. `libgeneric.ts` needs `RefObject` from `langsupport.ts` for its +`RefCollection` class, so it starts with: + +```ts +/// +``` + +## Host layers + +`pxsim.host` is what differs between a browser and Node: `Environment` (messaging the editor), +`Clock`, `Timers` and `RandomSource`. Each has a default that works without a browser. + +```ts +const t = host.clock().now(); // instead of Date.now() +const id = host.timers().setTimeout(fn, 20); // instead of setTimeout(fn, 20) +host.setClock({ now: () => fakeNow }); // replace one member; the rest keep their defaults +``` + +The browser installs its environment in `pxtsim/domhost.ts`: + +```ts +setEnvironment({ + postToParent: data => window.parent.postMessage(data, "*"), + locationHref: () => window.location.href, + ... +}); +``` + +`pxsim.audiohost` does the same for sound. Core plays through `audiohost.audio()`, and +`pxtsim/sound/audiohostdom.ts` registers the Web Audio implementation with `setAudioHost`. Without +it, core uses a silent host that plays nothing but takes the same time, so the metronome still +ticks. + +## The virtual host + +`createVirtualHost()` in `virtualhost.ts` returns a host whose clock advances only when the caller +advances it. Timers wait on a queue in virtual time and random numbers come from a seed, so runs +with the same seed are deterministic. + +```ts +const vh = pxsim.host.createVirtualHost({ seed: 1 }); +vh.use(); // install it as the current host +await vh.advance(1000); // fire everything due in the next second; no real time passes +await vh.runUntil(() => finished); // fire queued callbacks one at a time until finished is true +vh.stop(); +``` + +`advance` and `runUntil` yield to the event loop around each callback, so promises settle as they +would in a browser. The runtime yields about every 20 ms of host time. Virtual time does not advance +inside a busy loop, so the runtime also yields after a fixed number of checks on an unchanged clock, +and a stuck program yields to the caller instead of hanging Node. + +## Board state and view + +A board is a state, `runtime.board`, and an optional view, `runtime.boardView`. The state is +everything a program can read or change. The view draws it and turns user input into state changes. +With no view, the runtime skips every view call, so screenshots and recordings are no-ops. + +State code never calls the view. It requests a redraw, and the runtime calls the view's `updateView` +between steps: + +```ts +runtime.queueDisplayUpdate(); +``` + +A target sets both entry points. In pxt-microbit the view bundle sets one and the core bundle the +other: + +```ts +// sim/visuals/dalboardview.ts: state and view +if (!pxsim.initCurrentRuntime) pxsim.initCurrentRuntime = initRuntimeWithDalBoard; +// sim/core/headless.ts: state only +if (!pxsim.initHeadlessRuntime) pxsim.initHeadlessRuntime = initHeadlessDalBoard; +``` + +Shims and state code access the board through the target's `board()` accessor, and only view code +uses `boardView()`. Most states extend `CoreBoard`, which keeps part states in `builtinParts` and +stops sound on `kill`. A view implements `RuntimeBoardView`. The embed calls its `initAsync` after +the board's, and the program starts when both resolve. A view with breadboard parts passes its +`builtinVisuals` and the board state to `visuals.BoardHost`, which pairs each part view with its +state by simulation behavior. diff --git a/pxtsim/allocator.ts b/pxtsimcore/allocator.ts similarity index 99% rename from pxtsim/allocator.ts rename to pxtsimcore/allocator.ts index 3148630910e0..5b2cb3a359ff 100644 --- a/pxtsim/allocator.ts +++ b/pxtsimcore/allocator.ts @@ -11,12 +11,13 @@ namespace pxsim { // Used for finding the nearest available power pins getBBCoord: (loc: BBLoc) => visuals.Coord, }; - export interface AllocatorResult { + // TPart and TWire are the DOM-side part/wire types, which the allocator only stores. + export interface AllocatorResult { partsAndWires: PartAndWiresInst[]; requiresBreadboard?: boolean; hideBreadboard?: boolean; - parts: pxsim.visuals.IBoardPart[]; - wires: pxsim.visuals.Wire[]; + parts: TPart[]; + wires: TWire[]; } export interface PartInst { name: string, diff --git a/pxtsim/debugProtocol.ts b/pxtsimcore/debugProtocol.ts similarity index 99% rename from pxtsim/debugProtocol.ts rename to pxtsimcore/debugProtocol.ts index de35ca7038c4..1819ef97a68a 100644 --- a/pxtsim/debugProtocol.ts +++ b/pxtsimcore/debugProtocol.ts @@ -350,8 +350,8 @@ namespace pxsim.protocol { if (cb) { this._pendingRequests[request.seq] = cb; - const timer = setTimeout(() => { - clearTimeout(timer); + const timer = pxsim.host.timers().setTimeout(() => { + pxsim.host.timers().clearTimeout(timer); const clb = this._pendingRequests[request.seq]; if (clb) { delete this._pendingRequests[request.seq]; diff --git a/pxtsimcore/debugcore.ts b/pxtsimcore/debugcore.ts new file mode 100644 index 000000000000..dbf743bb3ae8 --- /dev/null +++ b/pxtsimcore/debugcore.ts @@ -0,0 +1,188 @@ +/// +/// + +namespace pxsim { + export function getWarningMessage(msg: string) { + let r: DebuggerWarningMessage = { + type: "debugger", + subtype: "warning", + breakpointIds: [], + message: msg + } + + let s = runtime.currFrame + while (s != null) { + r.breakpointIds.push(s.lastBrkId) + s = s.parent + } + + return r + } + + function valToJSON(v: any, heap: Map) { + switch (typeof v) { + case "string": + case "number": + case "boolean": + return v; + case "function": + return { + text: "(function)", + type: "function", + } + case "undefined": + return null; + case "object": + if (!v) return null; + if (v instanceof RefObject) { + if (heap) heap[(v as RefObject).id] = v; + let preview = RefObject.toDebugString(v); + let type = preview.startsWith('[') ? "array" : preview; + return { + id: (v as RefObject).id, + preview: preview, + hasFields: (v as any).fields !== null || preview.startsWith('['), + type: type, + } + } + if (v._width && v._height) { + return { + text: v._width + 'x' + v._height, + type: "image", + } + } + return { + text: "(object)", + type: "object", + } + default: + throw new Error(); + } + } + + export function dumpHeap(v: any, heap: Map, fields?: string[], filters?: string[], includeAll = false): Variables { + function frameVars(frame: any, fields?: string[]) { + const r: Variables = {} + for (let k of Object.keys(frame)) { + // skip members starting with __ + if (!/^__/.test(k) && /___\d+$/.test(k) && (!filters || filters.indexOf(k) !== -1)) { + r[k] = valToJSON(frame[k], heap) + } + } + if (frame.fields && fields) { + // Fields of an object. + for (let k of fields) { + k = k.substring(k.lastIndexOf(".") + 1); + r[k] = valToJSON(evalGetter(frame.vtable.iface[k], frame), heap); + } + } + if (frame.fields) { + for (let k of Object.keys(frame.fields).filter(field => includeAll || !field.startsWith('_'))) { + r[k] = valToJSON(frame.fields[k], heap) + } + } + else if (frame instanceof RefMap) { + for (const entry of frame.data) { + r[entry.key] = valToJSON(entry.val, heap); + } + } + else if (Array.isArray(frame.data)) { + // This is an Array. + (frame.data as any[]).forEach((element, index) => { + r[index] = valToJSON(element, heap); + }); + } + else if (frame._width !== undefined && frame._height !== undefined) { + // Probably a RefImage + r["width"] = frame._width; + r["height"] = frame._height; + + if (includeAll && frame._bpp !== undefined) { + r["isMono"] = frame._bpp === 1; + } + } + return r + } + + return frameVars(v, fields); + } + + /** Evaluates getter fn on target and returns its value. fn must have no side effects. */ + function evalGetter(fn: LabelFn, target: RefObject) { + let parentFrame: any = {}; + // We create a dummy stack frame + let stackFrame: any = { + pc: 0, + arg0: target, + fn, + parent: parentFrame + }; + + // And we evaluate the getter + while (stackFrame.fn) { + stackFrame = stackFrame.fn(stackFrame as any); + } + + return stackFrame.retval; + } + + export function injectEnvironmentGlobals(msg: DebuggerBreakpointMessage, heap: Map) { + const environmentGlobals = runtime.environmentGlobals; + const keys = Object.keys(environmentGlobals); + if (!keys.length) + return; + + const envVars: Variables = msg.environmentGlobals = {}; + Object.keys(environmentGlobals) + .forEach(n => envVars[n] = valToJSON(runtime.environmentGlobals[n], heap)) + } + + export function getBreakpointMsg(s: pxsim.StackFrame, brkId: number, userGlobals?: string[]): { msg: DebuggerBreakpointMessage, heap: Map } { + const heap: pxsim.Map = {}; + + const msg: DebuggerBreakpointMessage = { + type: "debugger", + subtype: "breakpoint", + breakpointId: brkId, + globals: dumpHeap(runtime.globals, heap, undefined, userGlobals), + stackframes: [], + } + + while (s != null) { + let info = getInfoForFrame(s, heap); + if (info) + msg.stackframes.push(info) + s = s.parent + } + + return { msg, heap }; + } + + function getInfoForFrame(s: pxsim.StackFrame, heap: any): StackFrameInfo { + let info = s.fn ? (s.fn as any).info : null + if (info) { + let argInfo: FunctionArgumentsInfo = { + thisParam: valToJSON((s as any).argL, heap), + params: [] + }; + + if (info.argumentNames) { + const args = info.argumentNames as string[]; + argInfo.params = args.map((paramName, index) => ({ + name: paramName, + value: valToJSON((s as any)["arg" + index], heap) + })); + } + + return { + locals: dumpHeap(s, heap), + funcInfo: info, + breakpointId: s.lastBrkId, + callLocationId: s.callLocIdx, + arguments: argInfo + }; + } + + return undefined; + } +} diff --git a/pxtsimcore/eventbus.ts b/pxtsimcore/eventbus.ts new file mode 100644 index 000000000000..491132ebfc9c --- /dev/null +++ b/pxtsimcore/eventbus.ts @@ -0,0 +1,145 @@ +namespace pxsim { + export type BoardPin = string; + export interface BBLoc { + type: "breadboard", + row: string, + col: string + xOffset?: number, + yOffset?: number, + style?: PinStyle; + }; + export interface BoardLoc { + type: "dalboard", + pin: BoardPin + }; + export type Loc = BBLoc | BoardLoc; + + export function mkRange(a: number, b: number): number[] { + let res: number[] = []; + for (; a < b; a++) + res.push(a); + return res; + } + + export class EventBus { + private queues: Map = {}; + private notifyID: number; + private notifyOneID: number; + private schedulerID: number; + private idleEventID: number; + private lastEventValue: string | number; + private lastEventTimestampUs: number; + private backgroundHandlerFlag: boolean = false; + + public nextNotifyEvent = 1024; + + constructor( + private readonly runtime: Runtime, + private readonly board: BaseBoard, + private readonly valueToArgs?: EventValueToActionArgs + ) { + this.schedulerID = 15; // DEVICE_ID_SCHEDULER + this.idleEventID = 2; // DEVICE_SCHEDULER_EVT_IDLE + + this.board.addMessageListener(this.handleMessage.bind(this)); + } + + private handleMessage(msg: pxsim.SimulatorMessage) { + if (msg.type === "eventbus") { + const ev = msg; + this.queue(ev.id, ev.eventid, ev.value); + } + } + + public setBackgroundHandlerFlag() { + this.backgroundHandlerFlag = true; + } + + public setNotify(notifyID: number, notifyOneID: number) { + this.notifyID = notifyID; + this.notifyOneID = notifyOneID; + } + + public setIdle(schedulerID: number, idleEventID: number) { + this.schedulerID = schedulerID; + this.idleEventID = idleEventID; + } + + private start(id: EventIDType, evid: EventIDType, background: boolean, create: boolean = false) { + let key = (background ? "back" : "fore") + ":" + id + ":" + evid + if (!this.queues[key] && create) this.queues[key] = new EventQueue(this.runtime, this.valueToArgs); + return this.queues[key]; + } + + listen(id: EventIDType, evid: EventIDType, handler: RefAction, flags = 0) { + // special handle for idle, start the idle timeout + if (id == this.schedulerID && evid == this.idleEventID) + this.runtime.startIdle(); + + let q = this.start(id, evid, this.backgroundHandlerFlag, true); + if (this.backgroundHandlerFlag) { + q.addHandler(handler, flags); + } + else { + q.setHandler(handler, flags); + } + this.backgroundHandlerFlag = false; + } + + removeBackgroundHandler(handler: RefAction) { + Object.keys(this.queues).forEach((k: string) => { + if (k.startsWith("back:")) + this.queues[k].removeHandler(handler) + }); + } + + // this handles ANY (0) semantics for id and evid + private getQueues(id: EventIDType, evid: EventIDType, bg: boolean) { + let ret = [this.start(0, 0, bg)] + if (id == 0 && evid == 0) + return ret + if (evid) + ret.push(this.start(0, evid, bg)) + if (id) + ret.push(this.start(id, 0, bg)) + if (id && evid) + ret.push(this.start(id, evid, bg)) + return ret + } + + queue(id: EventIDType, evid: EventIDType, value: EventIDType = null) { + if (runtime.pausedOnBreakpoint) return; + // special handling for notify one + const notifyOne = this.notifyID && this.notifyOneID && id == this.notifyOneID; + if (notifyOne) + id = this.notifyID; + let queues = this.getQueues(id, evid, true).concat(this.getQueues(id, evid, false)) + this.lastEventValue = evid; + this.lastEventTimestampUs = U.perfNowUs(); + + U.promiseMapAllSeries(queues, q => { + if (q) return q.push(value, notifyOne); + else return Promise.resolve() + }) + } + + queueIdle() { + if (this.schedulerID && this.idleEventID) + this.queue(this.schedulerID, this.idleEventID); + } + + // only for foreground handlers + wait(id: number | string, evid: number | string, cb: (value?: any) => void) { + let q = this.start(id, evid, false, true); + q.addAwaiter(cb); + } + + getLastEventValue() { + return this.lastEventValue; + } + + getLastEventTime() { + return 0xffffffff & (this.lastEventTimestampUs - runtime.startTimeUs); + } + } +} diff --git a/pxtsimcore/globals.d.ts b/pxtsimcore/globals.d.ts new file mode 100644 index 000000000000..80bbbd9977b7 --- /dev/null +++ b/pxtsimcore/globals.d.ts @@ -0,0 +1,59 @@ +// Declarations for the globals pxtsimcore may use. Core compiles without the DOM library, so these +// are declared by hand. Globals that only some hosts have may be undefined at run time. ImageData +// is the shape core reads from board view screenshots. +declare function setTimeout(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): any; +declare function clearTimeout(handle?: any): void; +declare function setInterval(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): any; +declare function clearInterval(handle?: any): void; +// Present in browsers and workers only. Check typeof before calling. +declare const requestAnimationFrame: ((callback: () => void) => any) | undefined; +declare const cancelAnimationFrame: ((handle: any) => void) | undefined; +// Present in Node only. Check typeof before calling. +declare const setImmediate: ((callback: () => void) => any) | undefined; +// Present in browsers, workers and Node. Check typeof before calling. +declare const MessageChannel: (new () => { + port1: { onmessage: ((event: any) => void) | null; close(): void }; + port2: { postMessage(message: any): void }; +}) | undefined; + +declare const console: { + log(...data: any[]): void; + debug(...data: any[]): void; + info(...data: any[]): void; + warn(...data: any[]): void; + error(...data: any[]): void; +}; + +declare const performance: { now(): number }; + +// Present in browsers, workers and Node. +declare function btoa(data: string): string; +declare function atob(data: string): string; + +declare class TextEncoder { + encode(input?: string): Uint8Array; +} + +declare class TextDecoder { + constructor(label?: string); + decode(input?: ArrayBuffer | ArrayBufferView): string; +} + +interface ImageData { + readonly width: number; + readonly height: number; + readonly data: Uint8ClampedArray; +} + +declare class URLSearchParams { + constructor(init?: string); + get(name: string): string | null; + set(name: string, value: string): void; +} + +declare class URL { + constructor(url: string, base?: string | URL); + readonly origin: string; + readonly searchParams: URLSearchParams; + toString(): string; +} diff --git a/pxtsim/host.ts b/pxtsimcore/host.ts similarity index 100% rename from pxtsim/host.ts rename to pxtsimcore/host.ts diff --git a/pxtsim/langsupport.ts b/pxtsimcore/langsupport.ts similarity index 100% rename from pxtsim/langsupport.ts rename to pxtsimcore/langsupport.ts diff --git a/pxtsim/libgeneric.ts b/pxtsimcore/libgeneric.ts similarity index 99% rename from pxtsim/libgeneric.ts rename to pxtsimcore/libgeneric.ts index 1f910b169963..287127d6414e 100644 --- a/pxtsim/libgeneric.ts +++ b/pxtsimcore/libgeneric.ts @@ -1,3 +1,5 @@ +/// + namespace pxsim { // A ref-counted collection of either primitive or ref-counted objects (String, Image, // user-defined record, another collection) diff --git a/pxtsim/localization.ts b/pxtsimcore/localization.ts similarity index 100% rename from pxtsim/localization.ts rename to pxtsimcore/localization.ts diff --git a/pxtsim/logger.ts b/pxtsimcore/logger.ts similarity index 100% rename from pxtsim/logger.ts rename to pxtsimcore/logger.ts diff --git a/pxtsimcore/messages.ts b/pxtsimcore/messages.ts new file mode 100644 index 000000000000..3f76b7c6d970 --- /dev/null +++ b/pxtsimcore/messages.ts @@ -0,0 +1,358 @@ +/// +/// + +namespace pxsim { + export interface SimulatorRunMessage extends SimulatorMessage { + type: "run"; + id?: string; + boardDefinition?: BoardDefinition; + frameCounter?: number; + refCountingDebug?: boolean; + options?: any; + parts?: string[]; + builtinParts?: string[]; + partDefinitions?: Map + fnArgs?: any; + code: string; + mute?: boolean; + highContrast?: boolean; + light?: boolean; + cdnUrl?: string; + localizedStrings?: Map; + version?: string; + clickTrigger?: boolean; + breakOnStart?: boolean; + storedState?: Map; + ipc?: boolean; + dependencies?: Map; + single?: boolean; + traceDisabled?: boolean; + activePlayer?: 1 | 2 | 3 | 4 | undefined; + theme?: string | pxt.Map; + yieldDelay?: number; + } + + export interface SimulatorInstructionsMessage extends SimulatorMessage { + type: "instructions"; + options: SimulatorInstructionsOptions; + } + + export interface SimulatorInstructionsOptions { + name: string; + boardDef: BoardDefinition; + parts: string[]; + partDefinitions: Map; + fnArgs: any; + configData: ConfigData; + print?: boolean; + } + + export interface SimulatorMuteMessage extends SimulatorMessage { + type: "mute"; + mute: boolean; + } + + export interface SimulatorStopSoundMessage extends SimulatorMessage { + type: "stopsound"; + } + + export interface SimulatorDocMessage extends SimulatorMessage { + type: "localtoken" | "docfailed"; + docType?: string; + src?: string; + localToken?: string; + } + + export interface SimulatorFileLoadedMessage extends SimulatorMessage { + type: "fileloaded"; + name: string; + // localeInfo NOT userLanguage + locale: string; + content?: string; + } + + export interface SimulatorReadyMessage extends SimulatorMessage { + type: "ready"; + frameid: string; + } + + export interface SimulatorTopLevelCodeFinishedMessage extends SimulatorMessage { + type: "toplevelcodefinished"; + } + + export interface SimulatorOpenDocMessage extends SimulatorMessage { + type: "opendoc"; + url: string; + } + + export type GlobalAction = "escape" | "toggleareamenu" | "togglekeyboardcontrolshelp"; + + export interface SimulatorActionMessage extends SimulatorMessage { + type: "action"; + action: GlobalAction; + } + + export interface SimulatorStateMessage extends SimulatorMessage { + type: "status"; + frameid?: string; + runtimeid?: string; + state: string; + } + export interface SimulatorBroadcastMessage extends SimulatorMessage { + broadcast: boolean; + toParentIFrameOnly?: boolean; + srcFrameIndex?: number; + } + + export interface SimulatorControlMessage extends SimulatorBroadcastMessage { + type: "messagepacket"; + channel: string; + data: Uint8Array; + } + + export interface SimulatorEventBusMessage extends SimulatorBroadcastMessage { + type: "eventbus"; + broadcast: true; + id: number; + eventid: number; + value?: number; + } + export interface SimulatorSerialMessage extends SimulatorMessage { + type: "serial"; + id: string; + data: string; + sim?: boolean; + csvType?: undefined | "headers" | "row" | "clear"; // if non-nullish pass to csv view instead + receivedTime?: number; + } + export interface SimulatorBulkSerialMessage extends SimulatorMessage { + type: "bulkserial"; + id: string; + data: { data: string, time: number }[]; + sim?: boolean; + } + export interface SimulatorCommandMessage extends SimulatorMessage { + type: "simulator", + command: "modal" | "restart" | "reload" | "setstate" | "focus" | "blur" | "single" + stateKey?: string; + stateValue?: any; + header?: string; + body?: string; + copyable?: string; + linkButtonHref?: string; + linkButtonLabel?: string; + displayOnceId?: string; // An id for the modal command, if the sim wants the modal to be displayed only once in the session + modalContext?: string; // Modal context of where to show the modal + timestamp?: number; + } + export interface SimulatorRadioPacketMessage extends SimulatorBroadcastMessage { + type: "radiopacket"; + broadcast: true; + rssi: number; + serial: number; + time: number; + + payload: SimulatorRadioPacketPayload; + } + export interface SimulatorInfraredPacketMessage extends SimulatorBroadcastMessage { + type: "irpacket"; + broadcast: true; + packet: Uint8Array; // base64 encoded + } + export interface SimulatorBLEPacketMessage extends SimulatorBroadcastMessage { + type: "blepacket"; + broadcast: true; + packet: Uint8Array; + } + export interface SimulatorI2CMessage extends SimulatorMessage { + type: "i2c"; + data: Uint8Array; + } + + export interface SimulatorRadioPacketPayload { + type: number; + groupId: number; + stringData?: string; + numberData?: number; + } + + export interface SimulatorCustomMessage extends SimulatorMessage { + type: "custom"; + content: any; + } + + export interface SimulatorScreenshotMessage extends SimulatorMessage { + type: "screenshot"; + data: ImageData; + delay?: number; + modalContext?: string; + } + + export interface SimulatorAutomaticThumbnailMessage extends SimulatorMessage { + type: "thumbnail"; + frames: ImageData[]; + } + + export interface SimulatorAddExtensionsMessage extends SimulatorMessage { + type: "addextensions", + /** + * List of repositories to add + */ + extensions: string[] + } + + export interface SimulatorAspectRatioMessage extends SimulatorMessage { + type: "aspectratio", + value: number, + frameid: string + } + + export interface SimulatorRecorderMessage extends SimulatorMessage { + type: "recorder"; + action: "start" | "stop"; + width?: number; + } + + export interface TutorialMessage extends SimulatorMessage { + type: "tutorial"; + tutorial: string; + subtype: string; + } + + export interface ImportFileMessage extends SimulatorMessage { + type: "importfile"; + filename: string; + parts: (string | ArrayBuffer)[]; + } + + export interface TutorialStepInfo { + fullscreen?: boolean; + contentMd?: string; + headerContentMd?: string; + hintContentMd?: string; + } + + export interface TutorialLoadedMessage extends TutorialMessage { + subtype: "loaded"; + showCategories?: boolean; + stepInfo: TutorialStepInfo[]; + toolboxSubset?: { [index: string]: number }; + } + + export interface TutorialStepChangeMessage extends TutorialMessage { + subtype: "stepchange"; + step: number; + } + + export interface TutorialFailedMessage extends TutorialMessage { + subtype: "error"; + message?: string; + } + + export interface RenderReadyResponseMessage extends SimulatorMessage { + source: "makecode", + type: "renderready", + versions: pxt.TargetVersions + } + + export interface RenderBlocksRequestMessage extends SimulatorMessage { + type: "renderblocks", + id: string; + code?: string; + options?: { + packageId?: string; + package?: string; + snippetMode?: boolean; + // only send back the svg: no png and no data uri (uri stays undefined) + svgOnly?: boolean; + } + } + + export interface RenderBlocksResponseMessage extends SimulatorMessage { + source: "makecode", + type: "renderblocks", + id: string; + svg?: string; + width?: number; + height?: number; + css?: string; + uri?: string; + error?: string; + } + + export interface SetActivePlayerMessage extends SimulatorMessage { + type: "setactiveplayer"; + playerNumber: 1 | 2 | 3 | 4 | undefined; + } + + export interface SetSimThemeMessage extends SimulatorMessage { + type: "setsimthemecolor"; + part: string; + color: string; + } + + export interface SetSimulatorThemeMessage extends SimulatorMessage { + type: "setsimtheme"; + theme: string | pxt.Map; + } + + export interface SetMuteButtonStateMessage extends SimulatorMessage { + type: "setmutebuttonstate"; + state: "muted" | "unmuted" | "disabled"; + } + + export namespace multiplayer { + type MessageBase = { + type: "multiplayer"; + origin?: "server" | "client"; + broadcast?: boolean; + }; + + export enum IconType { + Player = 0, + Reaction = 1, + } + + export type ImageMessage = MessageBase & { + content: "Image"; + image?: pxsim.RefBuffer; // pxsim.RefBuffer + palette: Uint8Array; + }; + + export type InputMessage = MessageBase & { + content: "Button"; + button: number; + clientNumber: number; + state: "Pressed" | "Released" | "Held"; + }; + + export type AudioMessage = MessageBase & { + content: "Audio"; + instruction: audiohost.SoundEvent; + soundbuf?: Uint8Array; + }; + + export type IconMessage = MessageBase & { + content: "Icon"; + icon?: pxsim.RefBuffer; // pxsim.RefBuffer + slot: number; + iconType: IconType; + // 48bytes, [r0,g0,b0,r1,g1,b1,...] + palette: Uint8Array; + }; + + export type ConnectionMessage = MessageBase & { + content: "Connection"; + slot: number; + connected: boolean; + } + + export type Message = + | ImageMessage + | AudioMessage + | InputMessage + | IconMessage + | ConnectionMessage; + } + +} diff --git a/pxtsim/runtime.ts b/pxtsimcore/runtime.ts similarity index 96% rename from pxtsim/runtime.ts rename to pxtsimcore/runtime.ts index 93d21381656c..676516e77f19 100644 --- a/pxtsim/runtime.ts +++ b/pxtsimcore/runtime.ts @@ -12,66 +12,6 @@ namespace pxsim { } export namespace U { - // Keep these helpers unified with pxtlib/browserutils.ts - export function containsClass(el: SVGElement | HTMLElement, classes: string) { - return splitClasses(classes).every(cls => containsSingleClass(el, cls)); - - function containsSingleClass(el: SVGElement | HTMLElement, cls: string) { - if (el.classList) { - return el.classList.contains(cls); - } else { - const classes = (el.className + "").split(/\s+/); - return !(classes.indexOf(cls) < 0); - } - } - } - - export function addClass(el: SVGElement | HTMLElement, classes: string) { - splitClasses(classes).forEach(cls => addSingleClass(el, cls)); - - function addSingleClass(el: SVGElement | HTMLElement, cls: string) { - if (el.classList) { - el.classList.add(cls); - } else { - const classes = (el.className + "").split(/\s+/); - if (classes.indexOf(cls) < 0) { - el.className.baseVal += " " + cls; - } - } - } - } - - export function removeClass(el: SVGElement | HTMLElement, classes: string) { - splitClasses(classes).forEach(cls => removeSingleClass(el, cls)); - - function removeSingleClass(el: SVGElement | HTMLElement, cls: string) { - if (el.classList) { - el.classList.remove(cls); - } else { - el.className.baseVal = (el.className + "") - .split(/\s+/) - .filter(c => c != cls) - .join(" "); - } - } - } - - function splitClasses(classes: string) { - return classes.split(/\s+/).filter(s => !!s); - } - - export function remove(element: Element) { - element.parentElement.removeChild(element); - } - - export function removeChildren(element: Element) { - while (element.firstChild) element.removeChild(element.firstChild); - } - - export function clear(element: Element) { - removeChildren(element); - } - export function assert(cond: boolean, msg = "Assertion failed") { if (!cond) { debugger diff --git a/pxtsim/sound/audiohost.ts b/pxtsimcore/sound/audiohost.ts similarity index 100% rename from pxtsim/sound/audiohost.ts rename to pxtsimcore/sound/audiohost.ts diff --git a/pxtsim/sound/instructions.ts b/pxtsimcore/sound/instructions.ts similarity index 100% rename from pxtsim/sound/instructions.ts rename to pxtsimcore/sound/instructions.ts diff --git a/pxtsim/sound/musicalProgressions.ts b/pxtsimcore/sound/musicalProgressions.ts similarity index 100% rename from pxtsim/sound/musicalProgressions.ts rename to pxtsimcore/sound/musicalProgressions.ts diff --git a/pxtsim/sound/sequencer.ts b/pxtsimcore/sound/sequencer.ts similarity index 100% rename from pxtsim/sound/sequencer.ts rename to pxtsimcore/sound/sequencer.ts diff --git a/pxtsim/sound/song.ts b/pxtsimcore/sound/song.ts similarity index 100% rename from pxtsim/sound/song.ts rename to pxtsimcore/sound/song.ts diff --git a/pxtsim/sound/soundEmojiSynthesizer.ts b/pxtsimcore/sound/soundEmojiSynthesizer.ts similarity index 100% rename from pxtsim/sound/soundEmojiSynthesizer.ts rename to pxtsimcore/sound/soundEmojiSynthesizer.ts diff --git a/pxtsim/sound/soundSynthesizer.ts b/pxtsimcore/sound/soundSynthesizer.ts similarity index 100% rename from pxtsim/sound/soundSynthesizer.ts rename to pxtsimcore/sound/soundSynthesizer.ts diff --git a/pxtsim/sound/soundSynthesizerEffects.ts b/pxtsimcore/sound/soundSynthesizerEffects.ts similarity index 100% rename from pxtsim/sound/soundSynthesizerEffects.ts rename to pxtsimcore/sound/soundSynthesizerEffects.ts diff --git a/pxtsim/sound/soundexpression.ts b/pxtsimcore/sound/soundexpression.ts similarity index 100% rename from pxtsim/sound/soundexpression.ts rename to pxtsimcore/sound/soundexpression.ts diff --git a/pxtsimcore/state/animationqueue.ts b/pxtsimcore/state/animationqueue.ts new file mode 100644 index 000000000000..c02abb6b0302 --- /dev/null +++ b/pxtsimcore/state/animationqueue.ts @@ -0,0 +1,75 @@ +namespace pxsim { + export interface AnimationOptions { + interval: number; + // false means last frame + frame: () => boolean; + whenDone?: (cancelled: boolean) => void; + setTimeoutHandle?: host.TimerHandle; + } + + export class AnimationQueue { + private queue: AnimationOptions[] = []; + private process: () => void; + + constructor(private runtime: Runtime) { + this.process = () => { + let top = this.queue[0]; + if (!top) return; + if (this.runtime.dead) return; + runtime = this.runtime; + let res = top.frame(); + runtime.queueDisplayUpdate(); + runtime.maybeUpdateDisplay(); + if (res === false) { + this.queue.shift(); + // if there is already something in the queue, start processing + if (this.queue[0]) { + this.queue[0].setTimeoutHandle = host.timers().setTimeout(this.process, this.queue[0].interval); + } + // this may push additional stuff + top.whenDone(false); + } else { + top.setTimeoutHandle = host.timers().setTimeout(this.process, top.interval); + } + } + } + + public cancelAll() { + let q = this.queue + this.queue = [] + for (let a of q) { + a.whenDone(true) + if (a.setTimeoutHandle) { + host.timers().clearTimeout(a.setTimeoutHandle); + } + } + } + + public cancelCurrent() { + let top = this.queue[0] + if (top) { + this.queue.shift(); + top.whenDone(true); + if (top.setTimeoutHandle) { + host.timers().clearTimeout(top.setTimeoutHandle); + } + } + } + + public enqueue(anim: AnimationOptions) { + if (!anim.whenDone) anim.whenDone = () => { }; + this.queue.push(anim) + // we start processing when the queue goes from 0 to 1 + if (this.queue.length == 1) + this.process() + } + + public executeAsync(anim: AnimationOptions) { + U.assert(!anim.whenDone) + return new Promise((resolve, reject) => { + anim.whenDone = resolve + this.enqueue(anim) + }) + } + } +} diff --git a/pxtsim/state/buttonpair.ts b/pxtsimcore/state/buttonpair.ts similarity index 100% rename from pxtsim/state/buttonpair.ts rename to pxtsimcore/state/buttonpair.ts diff --git a/pxtsim/state/compass.ts b/pxtsimcore/state/compass.ts similarity index 100% rename from pxtsim/state/compass.ts rename to pxtsimcore/state/compass.ts diff --git a/pxtsim/state/filesystem.ts b/pxtsimcore/state/filesystem.ts similarity index 100% rename from pxtsim/state/filesystem.ts rename to pxtsimcore/state/filesystem.ts diff --git a/pxtsim/state/lightsensor.ts b/pxtsimcore/state/lightsensor.ts similarity index 100% rename from pxtsim/state/lightsensor.ts rename to pxtsimcore/state/lightsensor.ts diff --git a/pxtsimcore/tsconfig.json b/pxtsimcore/tsconfig.json new file mode 100644 index 000000000000..5d986fdfbfd8 --- /dev/null +++ b/pxtsimcore/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es2017", + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "declaration": true, + "outFile": "../built/pxtsimcore.js", + "newLine": "LF", + "moduleResolution": "node", + "lib": [ + "es2017", + "ES2018.Promise" + ], + "types": [], + "skipLibCheck": true + }, + "include": [ + "**/*.ts" + ] +} diff --git a/pxtsim/utils.ts b/pxtsimcore/utils.ts similarity index 100% rename from pxtsim/utils.ts rename to pxtsimcore/utils.ts diff --git a/pxtsim/virtualhost.ts b/pxtsimcore/virtualhost.ts similarity index 100% rename from pxtsim/virtualhost.ts rename to pxtsimcore/virtualhost.ts diff --git a/pxtsimcore/visuals/boardgeometry.ts b/pxtsimcore/visuals/boardgeometry.ts new file mode 100644 index 000000000000..df59850fa4bd --- /dev/null +++ b/pxtsimcore/visuals/boardgeometry.ts @@ -0,0 +1,45 @@ +// DOM-free geometry, color and breadboard-layout helpers shared by the allocator and the visuals. +namespace pxsim.visuals { + export type Coord = [number, number]; + export function findDistSqrd(a: Coord, b: Coord): number { + let x = a[0] - b[0]; + let y = a[1] - b[1]; + return x * x + y * y; + } + export function findClosestCoordIdx(a: Coord, bs: Coord[]): number { + let dists = bs.map(b => findDistSqrd(a, b)); + let minIdx = dists.reduce((prevIdx, currDist, currIdx, arr) => { + return currDist < arr[prevIdx] ? currIdx : prevIdx; + }, 0); + return minIdx; + } + + export type WireColor = + "black" | "white" | "gray" | "purple" | "blue" | "green" | "yellow" | "orange" | "red" | "brown" | "pink"; + export const GPIO_WIRE_COLORS = ["pink", "orange", "yellow", "green", "purple"]; + export const WIRE_COLOR_MAP: Map = { + black: "#514f4d", + white: "#fcfdfc", + gray: "#acabab", + purple: "#a772a1", + blue: "#01a6e8", + green: "#3cce73", + yellow: "#ece600", + orange: "#fdb262", + red: "#f44f43", + brown: "#c89764", + pink: "#ff80fa" + } + export function mapWireColor(clr: WireColor | string): string { + return WIRE_COLOR_MAP[clr] || clr; + } + + // Pin rows and columns + export const BREADBOARD_MID_ROWS = 10; + export const BREADBOARD_MID_COLS = 30; + + // Row and column helpers + const alphabet = "abcdefghij".split("").reverse(); + export function getColumnName(colIdx: number): string { return `${colIdx + 1}` }; + export function getRowName(rowIdx: number): string { return alphabet[rowIdx] }; +}