### SharedInput Object Methods Source: https://penrose.cs.cmu.edu/bloom-docs/functions/useSharedInput Demonstrates how to interact with the SharedInput object, including setting and getting values, and integrating it into a diagram. ```APIDOC ## SharedInput Object Methods ### Description Shared inputs can be manipulated and accessed using methods on the `SharedInput` object. This includes setting new values, retrieving current values, and adding the shared input to a diagram builder. ### Usage #### Adding to Diagram ```javascript const myInput = db.sharedInput(mySharedInput); ``` #### Setting Value ```javascript myInput.set(5); ``` #### Getting Value ```javascript console.log(myInput.get()); // 5 ``` ``` -------------------------------- ### makePath Function Source: https://penrose.cs.cmu.edu/bloom-docs/functions/makePath Generates path data for a curve, taking start and end points, curve height, and padding as input. ```APIDOC ## makePath Function ### Description Generates path data for a curve with customizable height and padding. ### Method N/A (This is a function documentation, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **PathData** - Path data representing the generated curve. #### Response Example ```json { "path": "M 0 0 C 50 -50 150 -50 200 0" } ``` ``` -------------------------------- ### Diagram Class Methods Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram Provides details on how to add input effects, manage dragging, get diagram information, and render diagrams. ```APIDOC ## Diagram Class Methods ### addInputEffect * **Description**: Add an effect to an input. The effect will be called any time the input changes. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input. * **`fn`** ((val: number, name: string) => void) - Required - The effect function. * **`val`** (number) - The current value of the input. * **`name`** (string) - The name of the input. * **Returns**: void ### beginDrag * **Description**: Initiates a drag operation for a specified input. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input to begin dragging. * **Returns**: void ### discard * **Description**: Discards the current diagram state. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: void ### endDrag * **Description**: Ends a drag operation for a specified input. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input to end dragging for. * **Returns**: void ### getCanvas * **Description**: Retrieves the canvas properties of the diagram. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: Object - The canvas properties. * **`height`** (number) - The height of the canvas. * **`size`** ([number, number]) - The dimensions [width, height] of the canvas. * **`width`** (number) - The width of the canvas. * **`xRange`** (Range) - The range of the x-axis. * **`yRange`** (Range) - The range of the y-axis. ### getDraggingConstraints * **Description**: Retrieves the dragging constraints for the diagram. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: Map - A map of input names to their drag constraints. ### getInput * **Description**: Gets the current value of an input by its name. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input. * **Returns**: number - The value of the input. ### getInteractiveElement * **Description**: Returns an HTMLElement representing the interactive diagram. This element should be appended to a document node to be visible. It is styled by default with `"width: 100%; height: 100%; touch-action: none;"`. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: HTMLDivElement - The interactive diagram element. ### getOptimized * **Description**: Gets whether an input is set to be optimized. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input. * **Returns**: boolean - True if the input is optimized, false otherwise. ### optimizationStep * **Description**: Executes a single step of the diagram's optimization process. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: Promise - A promise that resolves to `true` if optimization should continue, or `false` if it should stop. ### removeInputEffect * **Description**: Removes an effect previously added to an input. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input. * **`fn`** ((val: number, name: string) => void) - Required - The effect function to remove. * **`val`** (number) - The current value of the input. * **`name`** (string) - The name of the input. * **Returns**: void ### render * **Description**: Renders the current state of the diagram as an SVG. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: Promise<{ nameElemMap: Map, svg: SVGSVGElement }> - A promise resolving to the SVG element and a map of shape names to SVG elements. ### renderStatic * **Description**: Renders the current state of the diagram as a static SVG. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: None * **Returns**: Promise - A promise resolving to the static SVG element. ### setInput * **Description**: Sets the value of an input by its name. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input. * **`val`** (number) - Required - The new value for the input. * **Returns**: void ### setOnInteraction * **Description**: Sets a callback function to be executed when an interaction occurs. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`fn`** (() => void) - Required - The callback function to execute on interaction. * **Returns**: () => void - A function to remove the interaction callback. ### setOnOptimizationFinished * **Description**: Sets a callback function to be executed when the optimization process finishes. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`fn`** ((xs: number[]) => void) - Required - The callback function to execute upon optimization completion. * **`xs`** (number[]) - An array of numbers representing the optimized values. * **Returns**: void ### setOnOptimizationStarted * **Description**: Sets a callback function to be executed when the optimization process starts. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`fn`** ((xs: number[]) => void) - Required - The callback function to execute when optimization begins. * **`xs`** (number[]) - An array of numbers representing the initial values. * **Returns**: void ### setOnOptimizationStepped * **Description**: Sets a callback function to be executed after each optimization step. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`fn`** ((xs: number[]) => void) - Required - The callback function to execute after each optimization step. * **`xs`** (number[]) - An array of numbers representing the current values after a step. * **Returns**: void ### setOptimized * **Description**: Sets whether an input should be optimized. * **Method**: N/A (Class method) * **Endpoint**: N/A * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **`name`** (string) - Required - The name of the input. * **`optimized`** (boolean) - Required - Whether the input should be optimized. ``` -------------------------------- ### Event Handlers for Penrose Bloom Interactions Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram This section describes methods for setting callback functions for various events, including general interaction, optimization start, step, and completion. It specifies the expected signature of these callback functions. ```javascript setOnInteraction(fn): (() => void) Parameters: fn: (() => void) ``` ```javascript setOnOptimizationFinished(fn): void Parameters: fn: ((xs: number[]) => void) ``` ```javascript setOnOptimizationStarted(fn): void Parameters: fn: ((xs: number[]) => void) ``` ```javascript setOnOptimizationStepped(fn): void Parameters: fn: ((xs: number[]) => void) ``` -------------------------------- ### Create and Use Shared Input with @penrose/bloom Source: https://penrose.cs.cmu.edu/bloom-docs/functions/useSharedInput Demonstrates how to create a shared input using the useSharedInput hook and add it to a Penrose diagram. It also shows how to set and get values from the shared input externally. ```javascript const myInput = db.sharedInput(mySharedInput); // ... later in the diagram definition ... myInput.set(5); console.log(myInput.get()); // 5 ``` -------------------------------- ### Implement diffusionProcess for Sampling from Diffusion Source: https://penrose.cs.cmu.edu/bloom-docs/functions/diffusionProcess This function samples 'n' points from a diffusion process starting at 'X0', using a covariance matrix 'A' and a constant drift 'omega'. It approximates the stochastic differential equation dX_t = omega dt + A dW_t, where W_t is a Wiener process. Requires 'n' (number of points), 'X0' (starting location), 'A' (covariance matrix), and 'omega' (drift direction). Returns a list of 'Vec2' points. ```typescript diffusionProcess(n: number, X0: Vec2, A: Vec2[], omega: Vec2): Vec2[] ``` -------------------------------- ### Accessing and Modifying Diagram Inputs Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram This covers functions for getting and setting input values by name. It also includes a method to set whether an input should be optimized. ```javascript getInput(name): number Parameters: name: string ``` ```javascript setInput(name, val): void Parameters: name: string val: number ``` ```javascript setOptimized(name, optimized): void Parameters: name: string optimized: boolean ``` -------------------------------- ### Implement unitMark2 function for line caps (@penrose/bloom) Source: https://penrose.cs.cmu.edu/bloom-docs/functions/unitMark2 The unitMark2 function in @penrose/bloom generates two points to cap a line segment. It requires the line's start and end points (optional start, implying an end point), a string 't' indicating whether to cap the 'start' or 'end' of the line, and a numeric 'size' for the cap. ```typescript unitMark2(start: [Vec2, Vec2], t: string, size: number): Vec2[] ``` -------------------------------- ### Connect Paths API Source: https://penrose.cs.cmu.edu/bloom-docs/functions/connectPaths Combines multiple path data objects into a single PathData object, connecting their start and end points. ```APIDOC ## POST /connectPaths ### Description Given a list of `PathData`s, returns a `PathData` representing the union of these paths with lines connecting the start and end points. ### Method POST ### Endpoint /connectPaths ### Parameters #### Request Body - **pathType** (string) - Required - Path type - **pathDataList** (PathData[]) - Required - List of path data ### Request Example ```json { "pathType": "", "pathDataList": [ { "points": [[0, 0], [1, 1]], "color": "red" }, { "points": [[1, 1], [2, 0]], "color": "blue" } ] } ``` ### Response #### Success Response (200) - **PathData** (object) - Connected path data #### Response Example ```json { "points": [[0, 0], [1, 1], [2, 0]], "color": "" } ``` ``` -------------------------------- ### Get an input by its name Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Retrieves an input variable by its specified name. This is useful for accessing predefined or user-defined inputs within the diagram. ```TypeScript getInput(name: string): Var ``` -------------------------------- ### MakePath Function Definition in Penrose Bloom Source: https://penrose.cs.cmu.edu/bloom-docs/functions/makePath Defines the makePath function which generates path data for a curve. It takes start and end points, curve height, and padding as input. The function is part of the @penrose/bloom package. ```typescript makePath(start: Vec2, end: Vec2, curveHeight: Num, padding: Num): PathData ``` -------------------------------- ### Connect Paths using @penrose/bloom Source: https://penrose.cs.cmu.edu/bloom-docs/functions/connectPaths The connectPaths function takes a path type and a list of PathData objects, returning a single PathData object that represents the union of the input paths. It connects the start and end points of the combined path. This function is part of the @penrose/bloom package. ```javascript connectPaths(pathType: string, pathDataList: PathData[]): PathData ``` -------------------------------- ### DiagramBuilder Constructor Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Initializes a new DiagramBuilder instance to construct diagrams. ```APIDOC ## new DiagramBuilder(canvas, variation?, lassoStrength?): DiagramBuilder ### Description Create a new diagram builder. ### Parameters #### Path Parameters * **canvas** (Canvas) - Required - Local dimensions of the SVG. This has no effect on the rendered size of your diagram--only the size of the local coordinate system. * **variation** (string) - Optional - Randomness seed * **lassoStrength** (number) - Optional - Strength of the optimizers lasso term. Higher values encourage diagram continuity, while lower values encourage reactivity. Default is 0. ### Returns DiagramBuilder ``` -------------------------------- ### Calculate Line Distance with shapeDistanceLines Source: https://penrose.cs.cmu.edu/bloom-docs/functions/shapeDistanceLines The shapeDistanceLines function calculates the distance between two lines defined by their start and end points. It requires four Vec2 parameters representing the start and end points of each line. The function returns a numerical value representing the calculated distance. ```typescript /** * Calculates the distance between two lines. * @param start1 The start point of the first line. * @param end1 The end point of the first line. * @param start2 The start point of the second line. * @param end2 The end point of the second line. * @returns The distance between the two lines. */ function shapeDistanceLines(start1: Vec2, end1: Vec2, start2: Vec2, end2: Vec2): Num; ``` -------------------------------- ### Instantiate DiagramBuilder Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Demonstrates how to create a new instance of the DiagramBuilder class. It shows the destructuring of the builder object to access its methods, and the required 'canvas' parameter for initialization. The 'variation' and 'lassoStrength' parameters are optional. ```javascript const { type, predicate, circle, line, ensure, // ... } = new DiagramBuilder(canvas(400, 400), "seed"); ``` -------------------------------- ### shapeDistanceLines Function Source: https://penrose.cs.cmu.edu/bloom-docs/functions/shapeDistanceLines Calculates the distance between two lines defined by their start and end points. ```APIDOC ## shapeDistanceLines ### Description Returns the distance between two lines. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Function Parameters - **start1** (Vec2) - Required - Start point of the first line. - **end1** (Vec2) - Required - End point of the first line. - **start2** (Vec2) - Required - Start point of the second line. - **end2** (Vec2) - Required - End point of the second line. ### Returns - **Num** - The distance between the two lines. ### Function Signature `shapeDistanceLines(start1: Vec2, end1: Vec2, start2: Vec2, end2: Vec2): Num` ### Example Usage ```javascript const distance = shapeDistanceLines(start1Vec, end1Vec, start2Vec, end2Vec); console.log(distance); ``` ``` -------------------------------- ### Rendering and Optimization in Penrose Bloom Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram This details methods for rendering the diagram, both statically and dynamically, and for performing optimization steps. It includes information on retrieving rendered elements and the results of optimization. ```javascript getCanvas(): { height: number; size: [number, number]; width: number; xRange: Range; yRange: Range; } ``` ```javascript getInteractiveElement(): HTMLDivElement Returns an HTMLElement presenting an interactive diagram. This element should be appended added to an existing document node to be visible. The element is styled by default with "width: 100%; height: 100%l touch-action: none". ``` ```javascript getOptimized(name): boolean Parameters: name: string ``` ```javascript optimizationStep(): Promise Take one optimization step. This will update the internal state of the diagram. Returns Promise `true` if the optimization should continue, `false` if it should stop (i.e. when optimization converges or fails) ``` ```javascript render(): Promise<{ nameElemMap: Map; svg: SVGSVGElement; }> ``` ```javascript renderStatic(): Promise ``` -------------------------------- ### Create Diagram Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram Creates a new renderable diagram from provided data. ```APIDOC ## POST /api/create_diagram ### Description Creates a new renderable diagram. It is recommended to use `DiagramBuilder.prototype.build` instead of calling this directly. ### Method POST ### Endpoint /api/create_diagram ### Parameters #### Request Body - **data** (DiagramCreationData) - Required - The data object used to create the diagram. ### Request Example { "data": { ... DiagramCreationData ... } } ### Response #### Success Response (200) - **Diagram** (Promise) - A promise that resolves with the created Diagram object. #### Response Example { "diagram": { ... Diagram Object ... } } ``` -------------------------------- ### input Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Creates a new input element with optional configuration. ```APIDOC ## input ### Description Create a new input. ### Method POST (Assumed) ### Endpoint `/api/inputs` (Assumed) ### Parameters #### Request Body - **info** (InputOpts) - Optional - InputOpts for the input ### Returns Var ``` -------------------------------- ### Center Interface Documentation Source: https://penrose.cs.cmu.edu/bloom-docs/interfaces/Center Details the properties and hierarchy of the Center interface. ```APIDOC ## Center Interface ### Description Represents a center point and drag properties within the Penrose Bloom library. ### Hierarchy - Drag - Center - Circle - Ellipse - Equation - Image - Rectangle - Text ### Properties #### center - **center** (Vec2) - Description of the center property. #### drag - **drag** (boolean) - Description of the drag property. #### dragConstraint - **dragConstraint** (DragConstraint) - Description of the dragConstraint property. ``` -------------------------------- ### DiagramBuilder build Method Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Details the 'build' method, which asynchronously compiles and renders the diagram. It returns a Promise that resolves with the final 'Diagram' object once the construction process is complete. ```javascript build(): Promise ``` -------------------------------- ### Get the current time input for animations Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Provides an input variable representing the time elapsed since the diagram was mounted. This is crucial for creating animations but requires the `AnimatedRenderer` component. ```TypeScript time(): Var ``` -------------------------------- ### DiagramBuilder Methods Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Provides methods for adding event listeners, binding inputs, building diagrams, and creating various shapes and constraints. ```APIDOC ## DiagramBuilder Methods ### addEventListener #### Description Adds an event listener to a shape. #### Parameters * **shape** (Shape) - Required * **event** (string) - Required * **listener** ((e: any, diagram: Diagram) => void) - Required * #### Parameters * **e** (any) - Required * **diagram** (Diagram) - Required #### Returns void ### bindToInput #### Description Create a new input, and constrain that input to a calculated value. This is useful for reading calculated values from the diagram using `getInput`, and for creating draggable values. #### Parameters * **num** (Num) - Required - Value to bind the input to * **info** (InputOpts) - Optional - `InputOpts` for the input #### Returns Var ### build #### Description Build the diagram. #### Returns Promise ### circle #### Description Create a new circle. Options: see https://penrose.cs.cmu.edu/docs/ref/style/shapes/circle #### Parameters * **_props** (Partial) - Optional - Properties for the circle #### Returns Readonly ### ellipse #### Description Create a new ellipse. Options: see https://penrose.cs.cmu.edu/docs/ref/style/shapes/ellipse #### Parameters * **_props** (Partial) - Optional - Properties for the ellipse #### Returns Readonly ### encourage #### Description Register an objective with the diagram. #### Parameters * **objective** (Num) - Required - A `Num` created with the `objectives` module. * **weight** (number) - Optional - An optional weight to multiply the objective by. #### Returns void ### ensure #### Description Register a constraint with the diagram. #### Parameters * **constraint** (Num) - Required - A `Num` created with the `constraints` module. * **weight** (number) - Optional - An optional weight to multiply the constraint by. #### Returns void ### equation #### Description Create a new equation. Options: see https://penrose.cs.cmu.edu/docs/ref/style/shapes/equation #### Parameters * **_props** (Partial) - Optional - Properties for the equation #### Returns Readonly ### forall #### Description Iterate over all possible assignments of substances to variables. This selection deduplicates assignments. #### Parameters * **vars** (SelectorVars) - Required * **func** ((assigned: SelectorAssignment, matchId: number) => void) - Required * #### Parameters * **assigned** (SelectorAssignment) - Required * **matchId** (number) - Required #### Returns void ### forallWhere #### Description Iterate over all possible assignments of substances to variables, subject to condition `where`. This selection does NOT deduplicate assignments. #### Parameters * **vars** (SelectorVars) - Required * **where** ((assigned: SelectorAssignment) => boolean) - Required * #### Parameters * **assigned** (SelectorAssignment) - Required * **func** ((assigned: SelectorAssignment, matchId: number) => void) - Required * #### Parameters * **assigned** (SelectorAssignment) - Required * **matchId** (number) - Required #### Returns void ``` -------------------------------- ### SharedInput Constructor Source: https://penrose.cs.cmu.edu/bloom-docs/classes/SharedInput Initializes a new SharedInput instance. It's recommended to use the `useSharedInput` hook instead of calling this constructor directly. It can take an initial value, an optimization flag, and a name. ```typescript new SharedInput(init?: number, optimized?: boolean, name?: string): SharedInput ``` -------------------------------- ### Calculate Distance Between Rectangle and Line Source: https://penrose.cs.cmu.edu/bloom-docs/functions/shapeDistanceRectLine Calculates the distance between a rectangle and a line segment. The rectangle is defined by its four corner points, and the line by its start and end points. Returns a numerical value representing the distance. ```javascript shapeDistanceRectLine(rect, start, end): Num ``` -------------------------------- ### type Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Creates a new substance type, which serves as a constructor for new substances. ```APIDOC ## type ### Description Create a new substance type. The type object serves as a constructor for new substances: ```javascript const Vector = type(); const v1 = Vector(); const v2 = Vector(); ... ``` ### Method POST (Assumed) ### Endpoint `/api/types` (Assumed) ### Returns Type ``` -------------------------------- ### Calculate Distance Between Rectangle and Line (TypeScript) Source: https://penrose.cs.cmu.edu/bloom-docs/functions/rectLineDist Computes the shortest distance between a rectangle and a line segment. The rectangle is defined by its bottom-left and top-right points, and the line segment by its start and end points. This function is part of the @penrose/bloom package. ```typescript rectLineDist(bottomLeft: Vec2, topRight: Vec2, start: Vec2, end: Vec2): Num ``` -------------------------------- ### Instantiate a new substance Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Creates a new instance of a substance. If a type is provided, it acts as a constructor for that type; otherwise, it creates an empty object. ```TypeScript substance(type?: Type): Substance ``` -------------------------------- ### Calculate Normal at Ray-Line Intersection (JavaScript) Source: https://penrose.cs.cmu.edu/bloom-docs/functions/rayIntersectNormalLine Calculates the normal vector at the point where a ray intersects a line segment. It takes the start and end points of the line, and a point and vector defining the ray. Returns the unit normal vector. ```javascript rayIntersectNormalLine(start, end, p, v): Vec2 // start: Vec2 // end: Vec2 // p: Vec2 // v: Vec2 ``` -------------------------------- ### substance Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Instantiates a new substance, optionally with a specified type. ```APIDOC ## substance ### Description Instantiate a new substance. If no type is given, this is identical to creating and empty object. If a type `T` is given, this method is equivalent to calling `T()`. ### Method POST (Assumed) ### Endpoint `/api/substances` (Assumed) ### Parameters #### Request Body - **type** (Type) - Optional - Type to instantiate ### Returns Substance ``` -------------------------------- ### Find Closest Point on Line - JavaScript Source: https://penrose.cs.cmu.edu/bloom-docs/functions/closestPointLine Calculates the closest point on a line segment defined by 'start' and 'end' points to a given point 'pt'. It returns a Vec2 representing the closest point. This function is part of the @penrose/bloom library. ```javascript closestPointLine(start, end, pt): Vec2 ``` -------------------------------- ### DiagramBuilder forall Method Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Details the 'forall' method, which iterates over all possible assignments of substances to variables for deduplicated selections. It takes 'vars' and a callback function that receives assignments and a match ID. ```javascript forall(vars, func): void ``` -------------------------------- ### vproduct: Entrywise Product Source: https://penrose.cs.cmu.edu/bloom-docs/variables/ops Calculates the entrywise product of two vectors, v1 and v2. The vectors must have the same length. ```APIDOC ## POST /vproduct ### Description Calculates the entrywise product of two vectors, v1 and v2. The vectors must have the same length. ### Method POST ### Endpoint /vproduct ### Parameters #### Request Body - **v1** (ad.Num[]) - Required - The first vector. - **v2** (ad.Num[]) - Required - The second vector. ### Request Example ```json { "v1": [1, 2, 3], "v2": [4, 5, 6] } ``` ### Response #### Success Response (200) - **output** (ad.Num[]) - The resulting vector with entrywise products. #### Response Example ```json { "output": [4, 10, 18] } ``` ``` -------------------------------- ### SelectorVars Type Alias in Penrose Bloom Source: https://penrose.cs.cmu.edu/bloom-docs/types/SelectorVars Defines the SelectorVars type alias, used to specify variable assignments in forall selectors. It's a record where keys are variable names and values are their types. Example demonstrates selecting over birds and trees. ```TypeScript type SelectorVars = Record; // Example: // { b1: Bird, b2: Bird, t: Tree } ``` -------------------------------- ### Calculate Circle-Line Distance with shapeDistanceCircleLine Source: https://penrose.cs.cmu.edu/bloom-docs/functions/shapeDistanceCircleLine Calculates the shortest distance between a circle and a line segment. It takes the circle's center and radius, and the line's start and end points as input. The function returns a numerical value representing this distance. ```javascript shapeDistanceCircleLine(c: Vec2, r: Num, start: Vec2, end: Vec2): Num ``` -------------------------------- ### Diagram Creation with DiagramBuilder Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram This snippet demonstrates how to create a renderable diagram using `DiagramBuilder.prototype.build`. It emphasizes passing a factory method to `useDiagram` for performance within React components. ```javascript DiagramBuilder.prototype.build ``` -------------------------------- ### Create a new input with optional configuration Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Generates a new input variable, optionally accepting an `InputOpts` object to configure its properties. Inputs are essential for dynamic diagram elements. ```TypeScript input(info?: InputOpts): Var ``` -------------------------------- ### Calculate Closest Point on Line Silhouette - JavaScript Source: https://penrose.cs.cmu.edu/bloom-docs/functions/closestSilhouettePointLine Calculates the closest point on the visibility silhouette of a line segment to a given point. It takes the start and end points of the line and the target point as input, returning the coordinates of the closest point. ```javascript closestSilhouettePointLine(start: Vec2, end: Vec2, p: Vec2): Vec2 ``` -------------------------------- ### Calculate Ray-Rectangle Intersection Distance Source: https://penrose.cs.cmu.edu/bloom-docs/functions/rayIntersectRectDistance Calculates the distance to the intersection of a ray with an axis-aligned rectangle. The function takes the rectangle's vertices, a starting point for the ray, and the ray's direction vector as input. It returns the distance to the closest intersection point. ```javascript rayIntersectRectDistance(rect, p, v): Num ``` -------------------------------- ### Create New Diagram (Penrose API) Source: https://penrose.cs.cmu.edu/bloom-docs/classes/Diagram Creates a new renderable diagram from provided data. It's recommended to use DiagramBuilder.prototype.build instead of calling this directly. Returns a Promise resolving to a Diagram object. ```javascript create(data): Promise ``` -------------------------------- ### Ray-Rectangle Intersection Calculation using rayIntersectRect Source: https://penrose.cs.cmu.edu/bloom-docs/functions/rayIntersectRect Calculates the intersection point of a ray with an axis-aligned rectangle. It takes the rectangle's corner points, a starting point for the ray, and the ray's direction vector as input. The function returns the intersection point as a Vec2. ```typescript rayIntersectRect(rect: Vec2[], p: Vec2, v: Vec2): Vec2 ``` -------------------------------- ### projectList Function Source: https://penrose.cs.cmu.edu/bloom-docs/functions/projectList Transforms a list of 3D object coordinates into window 2D coordinates. ```APIDOC ## projectList(P, model, proj, view) ### Description Transforms a list of 3D object coordinates $P = p_1, ldots, p_k$ into window 2D coordinates. ### Method Not Applicable (Function Signature) ### Endpoint Not Applicable (Function Signature) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **p** (Vec3[]) - Required - List of 3D object coordinates (x,y,z) * **model** (Num[][]) - Required - 4x4 modelview matrix * **proj** (Num[][]) - Required - 4x4 projection matrix * **view** (Vec4) - Required - viewport (x, y, width, height) ### Request Example None ### Response #### Success Response (200) * **Vec2[]** - List of projected 2D coordinates #### Response Example None ``` -------------------------------- ### Project 3D to 2D Coordinates using Penrose Bloom Source: https://penrose.cs.cmu.edu/bloom-docs/functions/project The `project` function transforms 3D object coordinates into 2D window coordinates using modelview, projection, and viewport matrices. It takes a 3D point `p` and matrices `model` and `proj`, along with a `view`port definition, returning the projected 2D coordinates. ```javascript project(p: Vec3, model: Num[][], proj: Num[][], view: Vec4): Vec2 ``` -------------------------------- ### Calculate Ray Intersection Distance with Polygon/Polyline Source: https://penrose.cs.cmu.edu/bloom-docs/functions/rayIntersectPolyDistance Calculates the distance from a point along a vector to the first intersection with a polygon or polyline. It requires an array of 2D points defining the shape, a boolean indicating if the shape is closed, the starting point of the ray, and the direction vector of the ray. ```javascript rayIntersectPolyDistance(pts: Vec2[], closed: boolean, p: Vec2, v: Vec2): Num ``` -------------------------------- ### Text Interface Properties Source: https://penrose.cs.cmu.edu/bloom-docs/interfaces/Text This section details all the properties of the Text interface, including their data types and descriptions. ```APIDOC ## Text Interface Properties ### Properties - **alignmentBaseline** (string) - The baseline alignment of the text. - **ascent** (Num) - The ascent of the text. - **center** (Vec2) - The center coordinates of the text. - **descent** (Num) - The descent of the text. - **dominantBaseline** (string) - The dominant baseline of the text. - **drag** (boolean) - Indicates if the text element is draggable. - **dragConstraint** (DragConstraint) - The constraint applied to dragging. - **ensureOnCanvas** (boolean) - Ensures the text stays on the canvas. - **fillColor** (Color) - The fill color of the text. - **fontFamily** (string) - The font family for the text. - **fontSize** (string) - The font size of the text. - **fontSizeAdjust** (string) - Adjusts the font size. - **fontStretch** (string) - Stretches the font. - **fontStyle** (string) - The font style (e.g., italic). - **fontVariant** (string) - The font variant (e.g., small-caps). - **fontWeight** (string) - The font weight (e.g., bold). - **height** (Num) - The height of the text bounding box. - **interactiveOnly** (boolean) - Makes the element interactive only. - **lineHeight** (string) - The line height of the text. - **name** (string) - The name of the text element. - **rotation** (Num) - The rotation angle of the text. - **shapeType** (Text) - Specifies the shape type as Text. - **string** (string) - The actual text content. - **strokeColor** (Color) - The stroke color of the text. - **strokeDasharray** (string) - The dash array for strokes. - **strokeStyle** (string) - The style of the stroke. - **strokeWidth** (Num) - The width of the stroke. - **textAnchor** (string) - The anchor point for text alignment. - **visibility** (string) - The visibility state of the text. - **width** (Num) - The width of the text bounding box. ``` -------------------------------- ### path Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Creates a new path shape. Accepts optional properties for customization. ```APIDOC ## path ### Description Create a new path. Options: see https://penrose.cs.cmu.edu/docs/ref/style ### Method POST (Assumed) ### Endpoint `/api/shapes/path` (Assumed) ### Parameters #### Request Body - **_props** (Partial) - Optional - Properties for the path ### Returns Readonly ``` -------------------------------- ### Generate Wedge Path Data (@penrose/bloom) Source: https://penrose.cs.cmu.edu/bloom-docs/functions/wedge Generates the SVG path data for a wedge shape. A wedge is an arc connected to the circle center and filled. It requires coordinates for the center, start, and end points, along with radius, rotation, and flags for arc size and sweep direction. ```javascript wedge(center, start, end, radius, rotation, largeArc, arcSweep): PathData ``` -------------------------------- ### SharedInput Class Source: https://penrose.cs.cmu.edu/bloom-docs/classes/SharedInput Provides methods for creating, managing, and interacting with shared input values within diagrams. ```APIDOC ## Class SharedInput An input that can be shared between diagrams and get/set from outside the diagram. You should call `useSharedInput` to create a shared input, rather than calling `new SharedInput` directly. ### Constructors #### constructor * `new SharedInput(init?, optimized?, name?): SharedInput` ##### Parameters * `init` (number) - Optional - Initial value for the input. * `optimized` (boolean) - Optional - Defaults to `false`. Indicates if the input is optimized. * `name` (string) - Optional - The name of the shared input. ##### Returns * `SharedInput` - A new instance of SharedInput. ### Properties #### `init` * `init?: number` * The initial value of the input. #### `name` * `name: string` * The name of the shared input. ### Methods #### addEffect * `addEffect(fn): void` * Add an effect to run when the value of the input changes. ##### Parameters * `fn` ((val: number) => void) - The effect function to add. It receives the new value as a number. ##### Returns * `void` #### get * `get(): null | number` * Get the current value of the input. ##### Returns * `null | number` - The current value, or null if not set. #### getOptimized * `getOptimized(): boolean` * Get whether the input is optimized. ##### Returns * `boolean` - True if the input is optimized, false otherwise. #### register * `register(diagram): void` * Registers a diagram with the shared input. ##### Parameters * `diagram` (Diagram) - The diagram to register. ##### Returns * `void` #### removeEffect * `removeEffect(fn): void` * Remove an effect added with `addEffect` from the input. ##### Parameters * `fn` ((val: number) => void) - The effect function to remove. ##### Returns * `void` #### set * `set(val): void` * Set the value of the input. This will update the value in all diagrams, and trigger a re-render for the component that created the input. ##### Parameters * `val` (number) - The new value to set for the input. ##### Returns * `void` #### unregister * `unregister(diagram): void` * Unregisters a diagram from the shared input. ##### Parameters * `diagram` (Diagram) - The diagram to unregister. ##### Returns * `void` ``` -------------------------------- ### arcSweepFlag Function (Penrose Bloom) Source: https://penrose.cs.cmu.edu/bloom-docs/functions/arcSweepFlag The arcSweepFlag function determines the direction of rotation for an arc. It returns 0 for counter-clockwise (CCW) rotation and 1 for clockwise (CW) rotation. It takes the start and end points of the arc as input, and optionally the center point (x1) of the circle or ellipse on which the arc is drawn. ```javascript function arcSweepFlag(x1, start, end) { // Returns 0 if direction of rotation is CCW, 1 if direction of rotation is CW. // Parameters: // x1: Vec2 (Optional) - x, y coordinates of the circle/ellipse that the arc is drawn on // start: Vec2 - start point of the arc // end: Vec2 - end point of the arc // Returns Num: 0 or 1 depending on CCW or CW rotation } ``` -------------------------------- ### Generate Circular Arc Path Data (Penrose Bloom) Source: https://penrose.cs.cmu.edu/bloom-docs/functions/circularArc The circularArc function generates path data for a circular arc. It requires the path type ('open' or 'closed'), the circle's center coordinates (Vec2), the radius (Num), and the start and end angles in radians (theta0, theta1). It returns PathData. ```javascript circularArc(pathType: string, center: Vec2, r: Num, theta0: Num, theta1: Num): PathData; ``` -------------------------------- ### DiagramBuilder circle Method Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Explains how to create a new circle shape using the 'circle' method. It accepts an optional 'Partial' object for configuring the circle's properties, referencing external documentation for available options. ```javascript circle(_props?): Readonly ``` -------------------------------- ### Join SVG PathData Objects Source: https://penrose.cs.cmu.edu/bloom-docs/functions/joinPaths The joinPaths function takes an array of PathData objects and concatenates them into a single PathData object. It assumes that the start and end points of consecutive PathData objects in the list already match, ensuring a continuous path. This function is crucial for generating complex SVG paths from multiple simpler segments. ```TypeScript import { PathData } from "@penrose/bloom/src/bloom/Paths"; /** * Given a list of PathData's, join them into one SVG path. * For correct results, the end points and start points of each path must already coincide. * * @param pathDataList List of path data * @returns Joined path data */ export function joinPaths(pathDataList: PathData[]): PathData ``` -------------------------------- ### Create an input from a SharedInput object Source: https://penrose.cs.cmu.edu/bloom-docs/classes/DiagramBuilder Initializes a new input variable using a `SharedInput` object, with an optional override for its initial value. This facilitates reusing input configurations. ```TypeScript sharedInput(input: SharedInput, initOverride?: number): Var ``` -------------------------------- ### Interface Poly Source: https://penrose.cs.cmu.edu/bloom-docs/interfaces/Poly Defines the structure and properties of the Poly interface. ```APIDOC ## Interface Poly ### Description Represents a polygonal shape with draggable behavior and constraints. ### Properties #### drag - **Type**: boolean - **Description**: Indicates whether the shape is draggable. #### dragConstraint - **Type**: DragConstraint - **Description**: Defines the constraints for dragging the shape. #### points - **Type**: Vec2[] - **Description**: An array of Vec2 points defining the vertices of the polygon. ### Hierarchy #### Parent Interfaces/Classes - Drag #### Child Interfaces/Classes - Polygon - Polyline ```