Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 21 additions & 4 deletions .github/instructions/simulator.instructions.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -31,15 +48,15 @@ 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

## 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
Expand Down
21 changes: 19 additions & 2 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(/^\/\/\/ <reference path="pxtsimcore\.d\.ts" \/>[ \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");
Expand Down Expand Up @@ -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)));
Expand Down Expand Up @@ -323,6 +337,7 @@ function updatestrings() {
"pxtlib",
"pxtpy",
"pxtsim",
"pxtsimcore",
"webapp/src",
"react-common"
], true);
Expand Down Expand Up @@ -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)))
Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion pxtlib/browserutils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down
2 changes: 1 addition & 1 deletion pxtlib/commonutil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = {};
let _translationsCache: pxt.Map<pxt.Map<string>> = {};
Expand Down
190 changes: 0 additions & 190 deletions pxtsim/debugger.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,4 @@
/// <reference path="./debugProtocol.ts" />
/// <reference path="./utils.ts" />

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 } = {};
Expand Down Expand Up @@ -83,176 +63,6 @@ namespace pxsim {
}
}

function valToJSON(v: any, heap: Map<any>) {
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<any>, 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<any>) {
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<any> } {
const heap: pxsim.Map<any> = {};

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;
Expand Down
Loading
Loading