Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(🗑️): Try to stabilize derived.with behavior #811

Draft
wants to merge 1 commit into
base: impr/proxy-value-prop
Choose a base branch
from
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
12 changes: 10 additions & 2 deletions packages/typegpu/src/core/function/tgpuFn.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Infer } from '../../data';
import type { Exotic, ExoticArray } from '../../data/exotic';
import type { AnyWgslData } from '../../data/wgslTypes';
import { inGPUMode } from '../../gpuMode';
import { getResolutionCtx, inGPUMode } from '../../gpuMode';
import type { TgpuNamable } from '../../namable';
import type {
Labelled,
Expand Down Expand Up @@ -95,7 +95,15 @@ export function fn<
does(
implementation: Implementation<InferArgs<Args>, InferReturn<Return>>,
): TgpuFn<Args, Return> {
return createFn(this, implementation as Implementation);
const fn = createFn(this, implementation as Implementation);

const ctx = getResolutionCtx();
if (ctx) {
// Creating a function during resolution.
const snapshot = Array.from(ctx.getSlotSnapshot());
return createBoundFunction(fn, snapshot);
}
return fn;
},
};
}
Expand Down
48 changes: 46 additions & 2 deletions packages/typegpu/src/resolutionCtx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ type ItemLayer = {

type SlotBindingLayer = {
type: 'slotBinding';
bindingMap: WeakMap<TgpuSlot<unknown>, unknown>;
bindingMap: Map<TgpuSlot<unknown>, unknown>;
};

type FunctionScopeLayer = {
Expand Down Expand Up @@ -105,7 +105,7 @@ class ItemStateStack {
pushSlotBindings(pairs: SlotValuePair<unknown>[]) {
this._stack.push({
type: 'slotBinding',
bindingMap: new WeakMap(pairs),
bindingMap: new Map(pairs),
});
}

Expand Down Expand Up @@ -154,6 +154,30 @@ class ItemStateStack {
return slot.defaultValue;
}

/**
* @returns A flattened list of slot->value pairs that are bound at the
* time of calling the function.
*/
getSlotSnapshot(): Iterable<SlotValuePair<unknown>> {
const flattened = new Map<TgpuSlot<unknown>, unknown>();

for (let i = this._stack.length - 1; i >= 0; --i) {
const layer = this._stack[i];

if (layer?.type === 'slotBinding') {
for (const [slot, value] of layer.bindingMap.entries()) {
// Since we're going bottom-up (or fine->coarse), we only
// acknowledge a slot if it hasn't been seen yet.
if (!flattened.has(slot)) {
flattened.set(slot, value);
}
}
}
}

return flattened.entries();
}

getResourceById(id: string): Resource | undefined {
for (let i = this._stack.length - 1; i >= 0; --i) {
const layer = this._stack[i];
Expand Down Expand Up @@ -372,6 +396,10 @@ class ResolutionCtxImpl implements ResolutionCtx {
return value;
}

getSlotSnapshot(): Iterable<SlotValuePair<unknown>> {
return this._itemStateStack.getSlotSnapshot();
}

withSlots<T>(pairs: SlotValuePair<unknown>[], callback: () => T): T {
this._itemStateStack.pushSlotBindings(pairs);

Expand Down Expand Up @@ -547,6 +575,22 @@ class ResolutionCtxImpl implements ResolutionCtx {
`Value ${value} (as json: ${JSON.stringify(value)}) of schema ${schema} is not resolvable to WGSL`,
);
}

resolveCall(fn: unknown, args: unknown[]): Resource {
if (isProviding(fn)) {
return this.withSlots(fn['~providing'].pairs, () =>
this.resolveCall(fn['~providing'].inner, args),
);
}

if (typeof fn === 'function') {
const result = fn(...args);
// TODO: Make function calls return resources instead of just values.
return { value: result, dataType: UnknownData };
}

throw new Error(`Cannot call ${fn} (as json: ${JSON.stringify(fn)}).`);
}
}

export interface ResolutionResult {
Expand Down
9 changes: 1 addition & 8 deletions packages/typegpu/src/smol/wgslGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
type ResolutionCtx,
type Resource,
UnknownData,
type Wgsl,
isWgsl,
} from '../types';

Expand Down Expand Up @@ -180,13 +179,7 @@ function generateExpression(
};
}

// Assuming that `id` is callable
// TODO: Pass in resources, not just values.
const result = (idValue as unknown as (...args: unknown[]) => unknown)(
...argValues,
) as Wgsl;
// TODO: Make function calls return resources instead of just values.
return { value: result, dataType: UnknownData };
return ctx.resolveCall(idValue, argValues);
}

assertExhaustive(expression);
Expand Down
7 changes: 7 additions & 0 deletions packages/typegpu/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@ export interface ResolutionCtx {
binding: number;
};

/**
* @returns A flattened list of slot->value pairs that are bound at the
* time of calling the function.
*/
getSlotSnapshot(): Iterable<SlotValuePair<unknown>>;

withSlots<T>(pairs: SlotValuePair<unknown>[], callback: () => T): T;

/**
Expand All @@ -119,6 +125,7 @@ export interface ResolutionCtx {

resolve(item: unknown): string;
resolveValue<T extends BaseWgslData>(value: Infer<T>, schema: T): string;
resolveCall(fn: unknown, args: unknown[]): Resource;

transpileFn(fn: string): {
argNames: string[];
Expand Down
9 changes: 4 additions & 5 deletions packages/typegpu/tests/derived.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,19 +183,18 @@ describe('TgpuDerived', () => {
});

it('allows slot bindings to pass downstream from derived (#697)', () => {
const utgpu = tgpu['~unstable'];
const valueSlot = utgpu.slot(1).$name('valueSlot');
const valueSlot = tgpu['~unstable'].slot(1).$name('valueSlot');

const derivedFn = utgpu.derived(() => {
return utgpu
const derivedFn = tgpu['~unstable'].derived(() => {
return tgpu['~unstable']
.fn([], d.f32)
.does(() => valueSlot.value)
.$name('innerFn');
});

const derivedFnWith2 = derivedFn.with(valueSlot, 2);

const mainFn = utgpu
const mainFn = tgpu['~unstable']
.fn([])
.does(() => {
derivedFn.value();
Expand Down