HelloWorld>>blankForm blankForm ^ (Form extent: 452@244 depth: 32) fillColor: Color white; yourself HelloWorld>>formForSize:line: formForSize: side line: lineWidth "Retain a centered Pen drawing so it survives window repaints." | form pen origin | form := self blankForm. origin := (form extent - (side@side)) // 2. pen := Pen newOnForm: form. pen defaultNib: lineWidth. pen color: (self colorFor: chosenColor). pen place: origin. pen north; turn: 90; down. 4 timesRepeat: [pen go: side; turn: 90]. pen up. ^ form HelloWorld>>drawSquare drawSquare | side line title | self resetFieldBorders. side := self integerFrom: sizeField text minimum: 40 maximum: 200. side ifNil: [^ self invalidField: sizeField message: 'Size must be a whole number from 40 to 200 pixels.']. line := self integerFrom: lineField text minimum: 1 maximum: 10. line ifNil: [^ self invalidField: lineField message: 'Line width must be a whole number from 1 to 10 pixels.']. title := (titleField text asString collect: [:character | character isSeparator ifTrue: [Character space] ifFalse: [character]]) withBlanksTrimmed. title size > 28 ifTrue: [^ self invalidField: titleField message: 'Please keep the drawing title to 28 characters or fewer.']. title isEmpty ifTrue: [title := 'My square']. titleText := title. sizeText := side asString. lineText := line asString. titleField setText: titleText. sizeField setText: sizeText. lineField setText: lineText. drawingMorph image: (self formForSize: side line: line). captionMorph contents: titleText. detailMorph contents: side asString, ' x ', side asString, ' px | ', line asString, ' px line | ', chosenColor asString capitalized. self status: 'Square drawn. Change the settings, then click Draw square.' error: false. ^ true HelloWorld>>chooseColor: chooseColor: aSymbol chosenColor := aSymbol. self updateColorButtons. self status: aSymbol asString capitalized, ' selected. Click Draw square to apply.' error: false HelloWorld>>integerFrom:minimum:maximum: integerFrom: aText minimum: minimum maximum: maximum | text number | text := aText asString withBlanksTrimmed. (text isEmpty or: [text size > 3]) ifTrue: [^ nil]. (text allSatisfy: [:character | character between: $0 and: $9]) ifFalse: [^ nil]. number := text asInteger. (number between: minimum and: maximum) ifFalse: [^ nil]. ^ number HelloWorld>>invalidField:message: invalidField: aField message: aString aField borderColor: self errorColor. self status: aString error: true. ^ false PenStarRecipe>>drawOn: drawOn: pen pen defaultNib: 3. pen color: (Color r: 0.50 g: 0.25 b: 0.85). 5 timesRepeat: [ pen go: 200; turn: 144]. PenRecordingPen>>go: go: distance | count increment | (distance isNumber and: [distance abs <= 2000]) ifFalse: [self error: 'go: needs a number between -2000 and 2000.']. count := ((distance abs / 8) ceiling) max: 1. increment := distance / count. count timesRepeat: [ location := location + ((direction degreeCos @ direction degreeSin) * increment). points add: location. self record: #go: arguments: {increment}] PenDrawingCommand>>executeOn:scale:offset: executeOn: aPen scale: factor offset: offset selector = #go: ifTrue: [^ aPen go: arguments first * factor]. selector = #place: ifTrue: [^ aPen place: arguments first * factor + offset]. selector = #goto: ifTrue: [^ aPen goto: arguments first * factor + offset]. ^ aPen perform: selector withArguments: arguments PenPlayground>>advanceOne advanceOne | command | messageIndex >= pendingCommands size ifTrue: [playing := false. ^ self]. [ command := pendingCommands at: messageIndex + 1. command executeOn: activePen scale: programScale offset: programOffset. messageIndex := messageIndex + 1. activeShape refreshDrawing. traceMorph contents: command description. self updateReadout. messageIndex = pendingCommands size ifTrue: [ playing := false. self status: 'Animation complete. Try another recipe or change the code.' error: false] ] on: Error do: [:error | playing := false. self status: 'Drawing: ', error description error: true] PenPlayground>>prepareProgram prepareProgram | source recorder block bounds factor form extent offset pen art old center action artRecipe | playing := false. source := codeField text asString. compileError := nil. recorder := PenRecordingPen new. [ [ source = currentRecipe source ifTrue: [currentRecipe drawOn: recorder] ifFalse: [ block := Compiler new evaluate: '[:pen | ', source, ']' in: nil to: self notifying: nil ifFail: [nil] logged: false. block ifNil: [ self status: 'Code: ', (compileError ifNil: ['Please check the syntax.']) error: true. ^ false]. block value: recorder] ] valueWithin: 2 seconds onTimeout: [self error: 'The program took too long. Use a finite loop.'] ] on: (Error, SyntaxErrorNotification) do: [:error | self status: 'Code: ', ((error isKindOf: SyntaxErrorNotification) ifTrue: [error errorMessage] ifFalse: [error description]) error: true. ^ false]. recorder commands isEmpty ifTrue: [ self status: 'No pen messages. Try pen go: 100.' error: true. ^ false]. bounds := recorder drawingBounds. factor := (1 min: (canvas width - 60) / (bounds width max: 1)) min: (canvas height - 60) / (bounds height max: 1). extent := ((bounds width * factor + 24) ceiling max: 28) @ ((bounds height * factor + 24) ceiling max: 28). form := Form extent: extent depth: 32. form fillColor: Color transparent. offset := (12@12) - (bounds origin * factor). pen := Pen newOnForm: form. pen defaultNib: 3. pen color: (self colorFor: #blue). pen place: offset; north; turn: 90; down. art := PenShapeMorph new. artRecipe := source = currentRecipe source ifTrue: [currentRecipe] ifFalse: [PenRecipe new]. art controller: self; recipe: artRecipe; form: form; penObject: pen. old := selectedShape. center := old ifNil: [canvas center] ifNotNil: [old center]. art center: center. self keepInsideCanvas: art. action := PenSceneCommand label: 'Draw ', artRecipe name do: [ old ifNotNil: [self detachShape: old]. self attachShape: art. self selectShape: art] undo: [ self detachShape: art. old ifNotNil: [self attachShape: old]. self selectShape: old]. self performCommand: action. activeShape := art. activePen := pen. pendingCommands := recorder commands. messageIndex := 0. programScale := factor. programOffset := offset. loadedSource := source. traceMorph contents: 'Prepared ', pendingCommands size asString, ' messages'. self updateReadout. ^ true PenCodeEditorMorph>>visibleLineNumbers visibleLineNumbers | lines rows textMorph textTop viewBounds y | pane ifNil: [^ #()]. textMorph := pane textMorph. lines := textMorph paragraph lines. rows := OrderedCollection new. textTop := textMorph boundsInWorld top - textMorph top. viewBounds := pane scroller boundsInWorld. lines withIndexDo: [:line :index | y := line top + textTop. ((y + line lineHeight > viewBounds top) and: [y < viewBounds bottom]) ifTrue: [rows add: {index. y. line lineHeight}]]. ^ rows PenCodeEditorMorph>>applyTheme: applyTheme: themeName | offset horizontal vertical | palette := PenLabTheme paletteFor: themeName. offset := pane scroller offset. horizontal := pane hScrollBar value. vertical := pane vScrollBar value. pane styler terminateBackgroundStylingProcess. self color: (palette at: #editor); borderColor: (palette at: #divider). pane color: (palette at: #editor); setTextColor: (palette at: #editorInk). pane textMorph caretColor: (palette at: #editorInk); selectionColor: (palette at: #selection); unfocusedSelectionColor: (palette at: #selection). pane textMorph paragraph caretColor: (palette at: #editorInk); selectionColor: (palette at: #selection); unfocusedSelectionColor: (palette at: #selection). gutter color: (palette at: #gutter). footer color: (palette at: #editorFooter). languageLabel color: (palette at: #muted). cursorLabel color: (palette at: #muted). pane hScrollBar color: (palette at: #gutter); sliderColor: (palette at: #divider). pane vScrollBar color: (palette at: #gutter); sliderColor: (palette at: #divider). pane styler palette: palette. pane updateStyleNow. pane hScrollBar value: horizontal. pane vScrollBar value: vertical. pane scroller offset: offset. pane changed. self refreshEditorChrome PenPlayground>>duplicateShape duplicateShape | original duplicate copiedPen | self ensureSelection ifFalse: [^ false]. playing := false. original := selectedShape. duplicate := PenShapeMorph new. duplicate controller: self; recipe: original recipe; form: original form deepCopy. original penObject ifNotNil: [ copiedPen := original penObject copy. copiedPen setDestForm: duplicate form. duplicate penObject: copiedPen]. duplicate restoreState: original state. duplicate position: original position + (22@16). self keepInsideCanvas: duplicate. self performCommand: (PenSceneCommand label: 'Duplicate' do: [self attachShape: duplicate. self selectShape: duplicate] undo: [self detachShape: duplicate. self selectShape: original]). self resetPlayback. self status: 'Shape duplicated. Drag either copy to arrange the scene.' error: false. ^ true PenPlayground>>recordMoveOf:from:to:label: recordMoveOf: art from: before to: after label: label | oldState newState | before = after ifTrue: [^ self]. oldState := before copy. newState := after copy. self performCommand: (PenSceneCommand label: label do: [art restoreState: newState. self selectShape: art] undo: [art restoreState: oldState. self selectShape: art]) PenPlayground>>performCommand: performCommand: command command execute. undoStack add: command. undoStack size > 30 ifTrue: [undoStack removeFirst]. redoStack removeAll. self updateSelectionLabel PenPlayground>>undo undo | command | undoStack isEmpty ifTrue: [^ self status: 'Nothing to undo.' error: false]. self resetPlayback. command := undoStack removeLast. command undo. redoStack add: command. self updateSelectionLabel. self status: 'Undid ', command label, '.' error: false PenPlayground>>redo redo | command | redoStack isEmpty ifTrue: [^ self status: 'Nothing to redo.' error: false]. self resetPlayback. command := redoStack removeLast. command execute. undoStack add: command. self updateSelectionLabel. self status: 'Redid ', command label, '.' error: false Lab3DMesh class>>torus torus | points polygons u v radial a b c d nextMajor nextMinor major minor | points := OrderedCollection new. polygons := OrderedCollection new. major := 30. minor := 12. 0 to: major - 1 do: [:row | u := row * 360 / major. 0 to: minor - 1 do: [:column | v := column * 360 / minor. radial := 1.02 + (0.40 * v degreeCos). points add: (Lab3DVector x: radial * u degreeCos y: 0.40 * v degreeSin z: radial * u degreeSin)]]. 0 to: major - 1 do: [:row | nextMajor := (row + 1) \\ major. 0 to: minor - 1 do: [:column | nextMinor := (column + 1) \\ minor. a := row * minor + column + 1. b := nextMajor * minor + column + 1. c := nextMajor * minor + nextMinor + 1. d := row * minor + nextMinor + 1. polygons add: {a. d. c. b}]]. ^ self vertices: points asArray faces: polygons asArray name: 'Torus' Lab3DRenderer>>render:extent:palette: render: aScene extent: extent palette: aPalette | started canvas records camera | started := Time millisecondClockValue. scene := aScene. palette := aPalette. (form isNil or: [form extent ~= extent]) ifTrue: [form := Form extent: extent depth: 32]. form fillColor: (palette at: #canvas). sineX := scene rotationX degreeSin. cosineX := scene rotationX degreeCos. sineY := scene rotationY degreeSin. cosineY := scene rotationY degreeCos. sineZ := scene rotationZ degreeSin. cosineZ := scene rotationZ degreeCos. focal := (extent x min: extent y) * 1.4 * scene zoom. origin := extent / 2.0. light := (Lab3DVector x: -0.6 y: 0.9 z: 1) normalized. canvas := BalloonCanvas on: form. scene axes ifTrue: [self drawGridOn: canvas]. records := OrderedCollection new. camera := Lab3DVector x: 0 y: 0 z: scene cameraDistance. scene meshes do: [:mesh | | viewVertices | viewVertices := mesh vertices collect: [:point | self rotate: (point * mesh scale) + mesh center]. mesh faces do: [:face | | points normal length center visible projected | points := face collect: [:index | viewVertices at: index]. normal := (points second - points first) cross: (points third - points first). length := normal magnitude. length > 0.000001 ifTrue: [ normal := normal * (1.0 / length). center := (points inject: (Lab3DVector x: 0 y: 0 z: 0) into: [:sum :point | sum + point]) * (1.0 / points size). visible := (normal dot: camera - center) > 0. ((visible or: [scene wireframe]) and: [points allSatisfy: [:point | scene cameraDistance - point z > 0.3]]) ifTrue: [ projected := points collect: [:point | self projectViewPoint: point]. records add: {center z. projected. self shade: mesh color normal: normal}]]]]. records := records asSortedCollection: [:a :b | a first <= b first]. drawnFaces := records size. records do: [:record | canvas drawPolygon: record second color: (scene wireframe ifTrue: [Color transparent] ifFalse: [record third]) borderWidth: (scene wireframe ifTrue: [1] ifFalse: [0]) borderColor: (scene wireframe ifTrue: [palette at: #message] ifFalse: [record third])]. renderMilliseconds := (Time millisecondClockValue - started) max: 0. renderCount := renderCount + 1. ^ form Lab3DRenderer>>projectViewPoint: projectViewPoint: point | distance factor | distance := scene cameraDistance - point z. distance <= 0.3 ifTrue: [^ nil]. factor := focal / distance. ^ (origin x + (point x * factor)) @ (origin y - (point y * factor)) Lab3DRenderer>>shade:normal: shade: base normal: normal | diffuse shine | diffuse := 0.27 + (0.73 * ((normal dot: light) max: 0)). shine := 0.10 * ((normal z max: 0) raisedTo: 18). ^ Color r: ((base red * diffuse + shine) min: 1) g: ((base green * diffuse + shine) min: 1) b: ((base blue * diffuse + shine) min: 1) Squeak3DLab>>runCode runCode | source candidate block candidateRenderer | playing := false. source := codeField text asString. source withBlanksTrimmed isEmpty ifTrue: [ self status: 'Choose a scene or enter a Smalltalk scene program.' error: true. ^ false]. candidate := Lab3DScene new. [ [ source = currentRecipe source ifTrue: [currentRecipe buildOn: candidate] ifFalse: [ block := Compiler new evaluate: '[:scene | ', source, ']' in: nil to: self notifying: nil ifFail: [nil] logged: false. block ifNil: [self error: 'Please check the Smalltalk syntax.']. block value: candidate]. candidate validate. candidateRenderer := Lab3DRenderer new. candidateRenderer render: candidate extent: canvas innerBounds extent palette: themePalette ] valueWithin: 2 seconds onTimeout: [self error: 'The scene program took too long. Use a finite loop.'] ] on: (Error, SyntaxErrorNotification) do: [:error | self status: 'Code: ', ((error isKindOf: SyntaxErrorNotification) ifTrue: [error errorMessage] ifFalse: [error description]) error: true. ^ false]. scene := candidate. canvas installScene: scene renderer: candidateRenderer. codeField bindName: 'scene' to: scene. loadedSource := source. frameIndex := 0. lastTick := 0. self updateModeButtons. self updateReadout. self status: 'Scene ready. Play to animate, drag to rotate, or inspect its live mesh.' error: false. ^ true Lab3DScene>>validate validate meshes isEmpty ifTrue: [self error: 'The scene needs a mesh.']. (self vertexCount > 5000 or: [self faceCount > 4000]) ifTrue: [self error: 'Keep the scene below 5000 vertices and 4000 faces.']. meshes do: [:mesh | mesh faces do: [:face | (face size < 3 or: [face anySatisfy: [:index | index isInteger not or: [(index between: 1 and: mesh vertices size) not]]]) ifTrue: [self error: 'A face contains invalid vertex indices.']]]. ^ true PenCodeEditorMorph>>bindName:to: bindName: name to: object (workspace bindingOf: name) value: object. pane updateStyleNow Lab3DMesh class>>cube cube | points | points := #((-1 -1 -1) (1 -1 -1) (1 1 -1) (-1 1 -1) (-1 -1 1) (1 -1 1) (1 1 1) (-1 1 1)) collect: [:triple | Lab3DVector x: triple first y: triple second z: triple third]. ^ self vertices: points faces: #((1 4 3 2) (5 6 7 8) (1 2 6 5) (4 8 7 3) (1 5 8 4) (2 3 7 6)) name: 'Cube' Squeak3DLab>>orbitBy: orbitBy: delta playing := false. scene rotateY: scene rotationY + (delta x * 0.6). scene rotateX: scene rotationX + (delta y * 0.6). canvas refresh. self updateReadout Squeak3DLab>>zoomIn zoomIn scene zoom: (scene zoom * 1.12 min: 2.2). canvas refresh. self updateReadout Squeak3DLab>>toggleWireframe toggleWireframe scene wireframe: scene wireframe not. canvas refresh. self updateModeButtons. self updateReadout Lab3DScene>>orbit orbit | sun blue green moon | kind := #orbit. time := 0. self resetView. sun := Lab3DMesh sphereSegments: 16 rings: 8 radius: 0.65. sun name: 'Sun'; color: (Color r: 1 g: 0.68 b: 0.18). blue := Lab3DMesh sphereSegments: 12 rings: 8 radius: 0.32. blue name: 'Blue planet'; color: (Color r: 0.20 g: 0.66 b: 1). green := Lab3DMesh sphereSegments: 12 rings: 8 radius: 0.24. green name: 'Outer planet'; color: (Color r: 0.35 g: 0.90 b: 0.66). moon := Lab3DMesh sphereSegments: 8 rings: 6 radius: 0.12. moon name: 'Moon'; color: (Color r: 0.88 g: 0.91 b: 1). meshes := OrderedCollection withAll: {sun. blue. green. moon}. self updateOrbits Lab3DScene>>advanceBy:speed: advanceBy: seconds speed: degreesPerSecond time := time + (seconds * degreesPerSecond). kind = #orbit ifTrue: [self updateOrbits] ifFalse: [self rotateY: rotationY + (seconds * degreesPerSecond)] Lab3DScene>>updateOrbits updateOrbits | phase firstCenter moonPhase outerPhase | phase := time. firstCenter := Lab3DVector x: 1.65 * phase degreeCos y: 0 z: 1.65 * phase degreeSin. meshes second center: firstCenter. outerPhase := phase * 0.63 + 140. meshes third center: (Lab3DVector x: 2.55 * outerPhase degreeCos y: 0.20 * phase degreeSin z: 2.55 * outerPhase degreeSin). moonPhase := phase * 3. meshes fourth center: firstCenter + (Lab3DVector x: 0.52 * moonPhase degreeCos y: 0.12 * moonPhase degreeSin z: 0.52 * moonPhase degreeSin) Squeak3DLab>>advanceSeconds: advanceSeconds: seconds scene advanceBy: seconds speed: self spinRate. frameIndex := frameIndex + 1. canvas refresh. self updateReadout Squeak3DLab>>animationTick animationTick | now elapsed | playing ifFalse: [^ self]. now := Time millisecondClockValue. elapsed := lastTick = 0 ifTrue: [25] ifFalse: [(now - lastTick) max: 1]. lastTick := now. lastFrameMilliseconds := elapsed. [self advanceSeconds: (elapsed / 1000.0 min: 0.1)] on: Error do: [:error | playing := false. self status: 'Scene: ', error description error: true] MorphicShowcase>>createItem: createItem: kind | item name fill | name := Dictionary newFrom: {#ellipse -> 'Ellipse'. #card -> 'Hello, Morphic'. #star -> 'Star'. #text -> 'Live Smalltalk'}. fill := Dictionary newFrom: { #ellipse -> self blueFill. #card -> self coralFill. #star -> self goldFill. #text -> (Color r: 0.07 g: 0.66 b: 0.52)}. item := MorphicDemoItem new kind: kind name: (name at: kind) color: (fill at: kind) controller: self; yourself. items add: item. canvas addMorph: item. ^ item MorphicShowcase>>resetScene resetScene | ellipse card star text | items copy do: [:item | item delete]. ellipse := self createItem: #ellipse. card := self createItem: #card. star := self createItem: #star. text := self createItem: #text. ellipse center: canvas position + (94@80). card center: canvas position + (276@78). star center: canvas position + (100@206). text center: canvas position + (278@208). snapEnabled := true. canvas showGrid: true. self layoutRow. self selectItem: card. self status: 'Drag a Morph into the drop zone. Change its color, animate it, or explore its native halo.' error: false MorphicDemoItem>>layoutContent layoutContent | insetExtent shown | insetExtent := (self extent - (12@12)) max: 12@12. content position: self position + (6@6). kind = #text ifTrue: [ content beAllFont: (TextStyle default fontOfSize: (17 * sizeFactor) rounded). content contents: displayName. content fit. shown := displayName. [content width > insetExtent x and: [shown size > 1]] whileTrue: [ shown := shown allButLast. content contents: shown, '...'; fit]. content center: self center] ifFalse: [ content extent: insetExtent. titleMorph ifNotNil: [ titleMorph font: (TextStyle default fontOfSize: ((12 * sizeFactor) rounded max: 7)). titleMorph contents: displayName. shown := displayName. [titleMorph width > insetExtent x and: [shown size > 1]] whileTrue: [ shown := shown allButLast. titleMorph contents: shown, '...']. titleMorph center: content center]] MorphicShowcase>>beginDragging: beginDragging: item item animated: false. canvas addMorphFront: item. self selectItem: item MorphicShowcase>>finishDragging: finishDragging: item | destination area local | destination := (dropZone bounds containsPoint: item center) ifTrue: [dropZone] ifFalse: [canvas]. destination addMorphFront: item. area := self usableBoundsFor: destination. snapEnabled ifTrue: [ local := item position - destination position. item position: destination position + (((local / 20) rounded) * 20)]. self fit: item in: area. dropZone borderColor: self borderColor. self selectItem: item. self status: (destination == dropZone ifTrue: ['Dropped. The same Morph now belongs to the drop-zone Morph. Drag it back to the stage.'] ifFalse: ['Dropped on the stage. Its native submorphs move with it.']) error: false MorphicShowcase>>fit:in: fit: item in: area | factor | factor := (area width / item width) min: (area height / item height). factor < 1 ifTrue: [item resizeTo: (item sizeFactor * factor * 0.96)]. self constrain: item to: area MorphicShowcase>>layoutDirection: layoutDirection: direction layoutDirection := direction. layoutBox listDirection: direction; layoutChanged; fullBounds. self updateLayoutButtons. statusMorph ifNotNil: [ self status: 'TableLayout repositioned the same three submorphs inside their container.' error: false] MorphicDemoItem>>step step | area next | (animated and: [self owner notNil]) ifFalse: [^ self]. area := controller usableBoundsFor: self owner. next := self position + velocity. (next x < area left or: [next x + self width > area right]) ifTrue: [velocity := velocity x negated @ velocity y]. (next y < area top or: [next y + self height > area bottom]) ifTrue: [velocity := velocity x @ velocity y negated]. self position: self position + velocity. controller constrain: self to: area. tickCount := tickCount + 1 MorphicDemoItem>>stepTime stepTime ^ 30