Claude Opus 5.5
Интерактивная 3D-игрушка «Jelly Press» на WebGPU: стальной пресс давит желейную арбузную дольку, один HTML-файл
Промпт
Создайте "Jelly Press": интерактивную 3D-игру в одном файле на HTML (все JS, CSS и шейдеры WGSL встроены, никаких внешних ресурсов, кроме Google Fonts). Рендеринг с помощью WebGPU; если WebGPU или адаптер отсутствуют, вместо пустой страницы отобразите чистое сообщение об ошибке. КОНЦЕПЦИЯ Четыре полупрозрачных желеобразных фруктовых дольки по очереди лежат на стальной плите гидравлического пресса. Игрок держит большую красную кнопку, чтобы опустить пресс. Желе сминается и растекается, манометр поднимается, и где-то после половины своей высоты оно разлетается на куски. После разрыва игра НЕ заканчивается: игрок может хватать куски, перетаскивать их, бросать и снова сминать. ЖЕЛЕ (чипы внизу, клавиши 1–4) 1. Долька арбуза (полудисковая плита): красная мякоть с темными семенами в форме слезы, бледная полоса корки, зеленая полосатая кожура. 2. Долька апельсина (полудиск): оранжевая мякоть, разделенная тонкими белыми мембранами, бледная сердцевина, апельсиновая кожура. 3. Половинка инжира: розовая мякоть, полная мелких золотистых семян, слой крема, темно-фиолетовая кожура. 4. Кольцо ананаса: золотистая волокнистая мякоть с радиальными прожилками и отверстием посередине. Каждое желе должно выглядеть как настоящее мармеладное лакомство: подповерхностное рассеивание, мягкая полупрозрачность, глянцевые блики, мягкие тени на теплом студийном полу (кремовый/бежевый, с тональной компрессией). ФИЗИКА (ЦП, фиксированный шаг 60 Гц) - Тетраэдрическое мягкое тело XPBD с 8 подшагами: ко-вращательное согласование формы тетраэдра, ограничения объема на тетраэдр, жесткие ограничения деформации ребер (0,35×–1,8×), демпфирование скорости ребер, контакт с полом с трением Кулона, сопротивление качению и мягкое оседание при почти полной неподвижности. - Рендер-меш, скиннингованный на ЦП через барицентрическое вложение в тетраэдры; нормали пересчитываются из треугольников каждый кадр. - Штамп пресса — кинематическая круглая плита (радиус ~1,05, скругленный край, толщина, сверху — поршень). Он действует как потолок с трением снизу, пол сверху и боковая стенка по ободу. Два столба пресса — твердые. - Показания давления в барах берутся из контактной нагрузки плиты, масштабированной по фруктам. РАЗРЫВ - Разрыв при случайном сжатии между 52% и 66% высоты желе. - Планируйте разрушение в фоновом режиме вскоре после начала каждого раунда, чтобы сам разрыв был мгновенным. - 5–7 больших кусков из 3D-ячеек Вороного со слегка наклонными стенками. На 3–4 из них дальний угол сколот двумя режущими плоскостями и разбит дальше на 2–4 мелких осколка, что оставляет зазубренные, выемчатые края. - Назначьте тетраэдры ячейкам по центроидам. Дублируйте частицы для каждого куска. Объедините крошечные островки с соседними. - Новое тело принимает старые положения и скорости. - Обрежьте треугольники скина по полупространствам каждой ячейки и заполните каждую разрезанную грань чистой плоской крышкой, показывающей внутреннюю часть фрукта (мякоть, семена, мембраны). Никаких растянутых треугольников, никаких дыр. - Отбросьте куски наружу и вверх от пресса. Мелкие осколки летят быстрее и выше и кувыркаются со случайным вращением. - Отобразите большой курсивный вердикт примерно на 2,5 с, затем плавно исчезните: "Шмяк." (дыня), "Выжато." (апельсин), "Ну, это джем." (инжир), "Раздавлено." (ананас). Включите строку статистики: "Сдался при N барах и N% высоты." ПОСЛЕ РАЗРЫВА: РЕЖИМ ИГРЫ - Захват: тест лучом/треугольником по скиннинговому мешу, с допустимым резервным вариантом в экранном пространстве для сенсорного ввода. - Захват прикрепляет захваченную область (радиус ~0,4, только частицы этого куска) к цели на плоскости перетаскивания, обращенной к камере. Мелкие осколки движутся целиком; большие куски растягиваются и раскачиваются, как желе. - Отпускание бросает кусок со скоростью указателя. - Куски сталкиваются друг с другом. Частица, найденная внутри тетраэдра другого куска, выталкивается через ближайшую грань скина этого куска с трением. Используйте широкую фазу AABB куска и пространственный хэш тетраэдров скина. - Куски остаются на сцене: боковые стенки, плюс невидимый передний край, чтобы ничего не оказалось под элементами управления или за камерой. - Пресс по-прежнему работает: удерживайте, чтобы снова смять куски (без второго разрыва); Подъем поднимает плиту. - Влажные звуки "плюх" при приземлении; небольшой хлюпающий звук при захвате. - Курсор: открытая рука над кусками,
Create "Jelly Press": a single-file interactive 3D toy in HTML (all JS, CSS and WGSL shaders inline, no external assets except Google Fonts). Render with WebGPU; if WebGPU or an adapter is missing, show a clean fallback message instead of a blank page. CONCEPT Four translucent gummy jellies shaped like fruit slices sit one at a time on the steel bed of a hydraulic press. The player holds a big red button to lower the press. The jelly squashes and spreads, the pressure gauge climbs, and somewhere past half its height it bursts into pieces. After the burst the game does NOT end: the player can grab the pieces, drag them, throw them around, and squash them again. THE JELLIES (chips at the bottom, keys 1–4) 1. Watermelon wedge (half-disc slab): red flesh with dark teardrop seeds, a pale rind band, a green striped skin. 2. Orange slice (half-disc): orange pulp segments separated by thin white membranes, pale pith, orange peel. 3. Fig half: pink flesh full of small golden seeds, a cream layer, a dark purple skin. 4. Pineapple ring: golden fibrous flesh with radial streaks and a hole in the middle. Each jelly should look like real gummy candy: subsurface scattering, soft translucency, glossy specular highlights, soft shadows on a warm studio floor (cream/beige, tone-mapped). PHYSICS (CPU, fixed 60 Hz step) - XPBD tetrahedral soft body with 8 substeps: co-rotational per-tet shape matching, per-tet volume constraints, hard edge strain limits (0.35×–1.8×), edge velocity damping, floor contact with Coulomb friction, rolling resistance, and gentle settling when nearly still. - Render mesh skinned on the CPU through barycentric embedding in the tets; normals recomputed from triangles every frame. - The press die is a kinematic round platen (radius ~1.05, rounded edge, a thickness, a ram above it). It acts as a ceiling with friction below, a shelf on top, and a side wall at its rim. The two press posts are solid. - Pressure readout in bar comes from the platen's contact load, scaled per fruit. THE BURST - Break at a random squash between 52% and 66% of the jelly's height. - Plan the fracture in the background shortly after each round starts, so the burst itself is instant. - 5–7 big pieces from 3D Voronoi cells with slightly tilted walls. On 3–4 of them, a far corner is chipped off by two cutting planes and split further into 2–4 small chips, which leaves jagged, notched edges. - Assign tets to cells by centroid. Duplicate particles per chunk. Merge tiny islands into their neighbours. - The new body adopts the old positions and velocities. - Clip the skin triangles against each cell's half-spaces, and fill every cut face with a clean flat cap showing the fruit's interior (flesh, seeds, membranes). No stretched triangles, no holes. - Kick pieces outward and upward from the press. Small chips fly faster and higher and tumble with random spin. - Show a big italic verdict for about 2.5 s, then fade it: "Splat." (melon), "Squeezed." (orange), "Well, that's jam." (fig), "Crushed." (pineapple). Include a stat line: "Gave up at N bar and N% of its height." AFTER THE BURST: PLAY MODE - Picking: ray/triangle test against the skinned mesh, with a forgiving screen-space fallback for touch. - Grabbing pins the grabbed patch (radius ~0.4, only particles of that chunk) to a target on a camera-facing drag plane. Small chips move whole; big pieces stretch and swing like jelly. - Releasing throws the piece with the pointer's velocity. - Pieces collide with each other. A particle found inside another chunk's tet is pushed out through that chunk's nearest skin face, with friction. Use a chunk AABB broad phase and a spatial hash of skin tets. - Pieces stay on stage: side walls, plus an invisible front edge so nothing ends up under the controls or behind the camera. - The press still works: hold to squash the pieces again (no second fracture); Raise lifts the platen. - Wet "plop" sounds on landings; a small squelch on grab. - Cursor: open hand over pieces, closed hand while dragging. Dragging empty space orbits the camera. UI (editorial, minimal) - Masthead top-left: "JELLY PRESS" in bold condensed caps, with "PRESS" filled in yellow/black hazard stripes. Subtitle: "Four gummies. One hydraulic press." - Top-right: Reset and Sound toggle. - Bottom deck: - Caption line with escalating captions while pressing: "Contact." → "It's fine. It's jelly." → "Getting wider." → "That's a pancake now." → "It's making a noise." → "Please." - Circular pressure dial (0–400 bar arc, red zone) around a red HOLD button, a Raise button, and a big numeric bar readout. - Fruit chips with icons. - In play mode the caption slot shows "Grab a piece. Throw it." with small "Press again" and "Next jelly" buttons. - Controls: hold Space or ArrowDown to press, ArrowUp to raise, R to reset, 1–4 to pick a fruit. Wheel zooms; double-click resets the view. - Camera: low bench-level view; the press frame yaws per fruit so the posts never block the jelly. Framing adapts so the jelly sits between masthead and deck; works on phones (portrait) with a narrower stage. SOUND (procedural Web Audio, no files) Hydraulic motor hum that rises with pressure, wet squelches, occasional creaks at high pressure, a valve clunk when the platen stops, a loud burst, soft plops on landing. Unlock on first interaction. QUALITY BAR - Smooth 60 fps on a laptop. - Background warm-up of the other fruits' meshes and shaders so switching is instant. - Respect prefers-reduced-motion. - Accessible labels, a gauge with role=meter, focus-visible outlines. - No console errors. The page never goes blank.
Права на промпт принадлежат автору @vib3coded. За коммерческое использование — продвижение нейросетей, агрегаторов, Telegram-ботов — отвечаете вы: mozgi.io ответственности не несёт. Подробнее →











