Filter
Exclude
Time range
-
Near
And a Contract (truncated here): # GAME CONTRACT — "Medieval Survivors", a 3D medieval survival RTS Stack: TypeScript strict Three.js 0.170 Vite. Zero external assets: every mesh is procedural low-poly built from primitives in src/meshes/common.ts. Single-player, runs in browser. Pitch: build a village economy (wood/stone/gold/iron wheat->flour->bread food chain, hunting, berries), raise an army, survive 10 escalating night raids. Lose if the Town Hall falls. ## Conventions - Y up. World is WORLD.size x WORLD.size units centered at origin (x,z in [-128, 128]). Every entity sits at y = ctx.terrain.getHeight(x, z). - Grid: WORLD.gridCells=128 cells/side, cellSize=2. Cell (cx,cz) spans world x in [cx*2-128, cx*2-126]. Cell center x = cx*2 - 128 1. - Buildings occupy size x size cells, (cx,cz) = MIN corner. Building center world x = (cx size/2)*2 - 128, same formula for z. Footprint world width = size*2. - Humans are ~1.8 units tall. Units face movement direction: group.rotation.y = Math.atan2(dx, dz) (rotation 0 faces Z). - Interaction ranges (dist measured in XZ plane): gather node when dist <= node.radius 1.5; build/repair when dist <= building.size 1.8 (size in cells = half footprint in world units); melee hit when dist <= attackRange target.radius. - update(ctx, dt): dt is game-seconds, pre-scaled by speed, 0 while paused. Called every frame. - Cross-module references use the interfaces in src/types.ts. Concrete class imports allowed ONLY where this contract names them. - Resources are floats internally; UI displays Math.floor. ## File-by-file contract ### src/core/eventBus.ts export class EventBus implements IEventBus — Map of event name to Set of callbacks. ### src/core/input.ts export class InputManager implements IInput. constructor(dom: HTMLElement). Tracks held keys lowercase. Left mouse: < 6px movement = click (onClick); >= 6px = drag-select — while dragging, position/size the #select-box div (display block, left/top/width/height px), on mouseup hide it and fire onDragSelect with NDC min/max corners. Right click fires onRightClick and suppresses contextmenu. pointer NDC kept current on mousemove. onKeyDown fires with e.key.toLowerCase() (e.g. 'escape', ' ', 'f1'). ### src/core/cameraController.ts export class CameraController implements ICameraController. constructor(camera: THREE.PerspectiveCamera, dom: HTMLElement, keys: Set<string>). Classic RTS rig orbiting a ground target point: yaw rotates with q/e, zoom distance 25..110 via wheel, pitch ~0.9 rad. Pan with wasd/arrow keys relative to current yaw, plus edge-of-screen pan (within 14px of window edge) — pan speed proportional to zoom. panTo(x,z) recenters. Clamp target to /-(WORLD.size/2 - 10). update(dt) receives REAL unscaled dt (camera works while paused). Camera position = target spherical offset; camera.lookAt(target). ### src/core/sound.ts export class SoundManager implements ISound. Pure WebAudio synthesis (oscillators, noise buffers, gain envelopes) — distinct character per SoundName: chop=woody knock, mine=stone clink, build=hammer tap, place=thud, train=short fanfare blip, attack=swish, arrow=whoosh, death=low groan, horn=long low brass swell (wave warning), coin=bright ding, error=dull buzz, click=tick, victory=rising fanfare, defeat=falling minor phrase, upgrade=anvil ring, harvest=rustle. AudioContext created/resumed lazily on first pointerdown/keydown (addEventListener on window). 80ms per-name throttle. Master gain 0.18. toggleMute() returns new muted state. ### src/world/noise.ts export function makeNoise2D(seed: number): (x: number, y: number) => number — seeded value noise, smooth interpolation, output [-1,1]. export function fbm(n: (x: number, y: number) => number, x: number, y: number, octaves?: number, lacunarity?: number, gain?: number): number — defaults 4/2/0.5, output approx [-1,1]. ### src/world/terrain.ts export class Terrain implements ITerrain. constructor(seed: number). A continuous private heightAt(x,z) built from fbm (scale so hills roll gently, height 0..WORLD.maxTerrainHeight); flatten toward height 3.2 within WORLD.startClearRadius*1.4 of origin (fully flat inside startClearRadius); carve one lake in a quadrant far from center by smoothly depressing heights below WORLD.waterLevel. mesh = PlaneGeometry(WORLD.size, WORLD.size, 160, 160) rotated flat, vertex y from heightAt, VERTEX COLORS: sandy near water level, grass greens with noise-driven dirt patches, gray rock on steep slopes, lighter dry grass on high ground. material MeshLambertMaterial vertexColors. receiveShadow true, castShadow false. getHeight(x,z) = heightAt (same function = mesh matches exactly). isWater(x,z) = heightAt < WORLD.waterLevel. ### src/world/water.ts export class Water. constructor(). mesh: PlaneGeometry(WORLD.size, WORLD.size, 32, 32) at y = WORLD.waterLevel - 0.05, MeshLambertMaterial color PALETTE.water transparent opacity 0.78. update(dt): gently undulate a few vertices / bob y by -0.04 for a living-water feel. ### src/world/grid.ts export class Grid implements IGrid. constructor(terrain: ITerrain). Precompute per-cell terrainOk: cell center not water AND |slope| ok (max height difference between center and samples -cellSize < 2.2). occupancy = Int32Array(cells*cells) of entity id or 0. isWalkable = inBounds && terrainOk && occupancy 0. canPlace(cx,cz,size) = every footprint cell inBounds && terrainOk && unoccupied. occupy/free write the footprint. blockerAt returns occupancy value. ### src/world/dayNight.ts export class DayNightCycle implements IDayNight. constructor(scene: THREE.Scene). Owns: HemisphereLight ambient, sun DirectionalLight (castShadow, 2048 map, ortho frustum ~ -110, bias tuned ~-0.0005), dim bluish moon DirectionalLight (no shadow), scene.background THREE.Color and scene.fog (new THREE.Fog) lerped through dawn/noon/dusk/night palettes, a Points starfield only visible at night (transparent material, opacity fades), small glowing sun & moon sphere meshes orbiting the sky far out. day starts at 1, time starts 0.25 (morning). update(ctx, dt): time = dt/TIME.dayLength; on wrap past 1: time -= 1, day , emit bus dayChanged; when crossing (1 - TIME.nightFraction) emit nightFell. isNight = time > 1 - TIME.nightFraction. lightLevel: smooth 1.0 at midday -> 0.12 deep night. Sun shadow camera recentered on ctx.cameraCtrl.target each frame (snap to whole units to avoid shimmer). ### src/world/worldGen.ts export function generateWorld(ctx: IGameCtx, seed: number): void. Uses rng(seed) from common.ts. MAY import concrete classes ResourceNode (src/entities/resourceNode) and Animal (src/entities/animal). Spawns via ctx.addNode / ctx.addAnimal (game handles grid occupancy scene add). Placement guards: skip water cells, skip dist<WORLD.startClearRadius from origin (except berry/sheep noted), skip already-occupied cells. Content: WORLD.treeCount trees in organic clusters of 8-20 (pineRatio of them pine, pines favor higher ground); WORLD.rockCount rocks in small outcrop groups; goldMines ironDeposits scattered mid-distance (45-110 from center); berryClusters of bushesPerBerryCluster bushes at 30-55 from center; deerHerds of deerPerHerd boars roaming far; sheep near start (12-22 from center); WORLD.propCount decorative props (flowers/bushes/mushrooms/logs — NOT entities: build prop groups, set position terrain height, add directly to ctx.scene, no occupancy). ### src/meshes/props.ts All return THREE.Group, statically baked via bakeGroup for single draw call. exports: makeTree(variant: number), makePine(variant: number), makeRock(variant: number), makeGoldMine(), makeIronDeposit(), makeBerryBush(), makeCarcass(kind: AnimalKind), makeCropField(stage: number, size: number), makeProp(variant: number), makeStump(). Trees 4-6u tall, trunk 2-3 foliage blobs, per-variant randomness via rng(variant). Pine = stacked cones. Goldmine: rock mound gold nuggets dark entrance timber supports (radius ~2.2 visual). Iron deposit: gray rock metallic chunks. Berry bush: green blob berry dots. Carcass: lying animal form, bone accents. makeCropField: rows of wheat stalks on dirt — stage 0 bare tilled rows, 1 green sprouts, 2 waist-high green, 3 tall golden wheat; field spans size x size world units centered on origin of the group. makeProp variants: flower patch, shrub, mushrooms, fallen log. ### src/meshes/buildings.ts export function makeBuildingMesh(kind: BuildingKind): THREE.Group — DETAILED and distinctive, 15-40 primitives each, scaled to footprint (def size*2 world units): townhall = grand two-story timber-framed hall, stone base, banners, torch posts; house = cottage w/ thatched roof chimney; farm = low fence enclosing a dirt field tiny tool shed, and group.userData.cropAnchor = a THREE.Object3D placed at the field center (crop visuals get attached there by the Building entity; field clear span ~4.2u); mill = stone tower windmill with a 4-blade rotor — rotor NOT baked, group.userData.animate = (t: number) => rotor rotates; bakery = stone oven dome chimney awning; granary = raised storehouse on stilts sacks; lumbercamp = log piles saw bench; quarry = stone piles cart; barracks = squat stone fort banner weapon rack; archery = open range with target butts fence; stable = barn paddock fence; blacksmith = open forge: anvil, orange glowing forge (MeshLambertMaterial w/ emissive orange; userData.animate pulses emissiveIntensity); wall = 2u-wide stone wall segment ~2.6u tall w/ crenellation; tower = slim stone watchtower ~7u tall, crenellated platform; well = stone ring little roof bucket; market = colorful awning stalls crates barrels. Static parts composed then baked with bakeGroup; animated subparts (rotor, forge glow) added to the returned group AFTER baking so they stay live. Every group origin = footprint center at ground level. export function makeConstructionSite(size: number): THREE.Group — wooden scaffold poles planks roughly covering a size*2 footprint. Animation convention: group.userData.animate?: (t: number) => void — game calls it each frame with ctx.time for every BUILT building. ### src/meshes/units.ts export function makeHumanoid(kind: UnitKind | EnemyKind): HumanoidRig. Blocky humanoid ~1.8u: head, torso, 2 arms, 2 legs — arms/legs are pivot Groups anchored at shoulder/hip so rotation.x swings naturally. Distinct outfits: villager tunic straw hat; swordsman iron helm round shield on left arm; archer green hood back quiver; knight full plate plume, bulkier; raider dark furs warpaint; brute oversized shoulder spikes; shaman robe skull mask; warlord large horned helm red cape. kind 'wolf' returns a gray quadruped rig instead (same HumanoidRig interface; setTool/setCarry are no-ops for it). setWalkPhase(p): legs/arms swing ~sin(p); setIdle(): limbs ease to rest; setAttackPhase(q in 0..1): right (tool) arm winds up and swings through; setTool attaches the named tool mesh to the right hand (axe pick hammer sword bow scythe club staff; null removes); setCarry shows a sack/log bundle held in front (null removes). export function makeAnimal(kind: AnimalKind): AnimalRig — deer slender antlers, boar stocky tusks, sheep wool blob; 4 leg pivots; setWalkPhase trots, setIdle rests. ### src/meshes/fx.ts export function makeSelectionRing(radius: number, color?: number): THREE.Mesh — RingGeometry flat on ground (rotation.x = -PI/2), y 0.06, depthWrite false, default green 0x66ff66. export function makeHealthBar(width?: number): IHealthBar — THREE.Sprite using a small canvas texture; set(frac) repaints green->yellow->red fill; setVisible toggles. export function makeArrow(): THREE.Group — fletched arrow ~0.9u pointing Z. export class Particles implements IParticles — pool of ~300 small colored boxes; burst(pos,color,count=10,speed=6) launches with random velocity gravity, shrink/fade, auto-recycle; update(dt). Constructor takes scene: THREE.Scene and adds itself. export function makeRallyFlag(): THREE.Group — small pennant on a pole. export function makeGhostMaterials(): { valid: THREE.Material; invalid: THREE.Material } — transparent green / red (opacity ~0.55, depthWrite false). ### src/entities/entity.ts export abstract class Entity implements IEntity. Static id counter. constructor builds group; subclass attaches meshes. healthBar (makeHealthBar) floated above (per-entity height offset), visible only when hp < maxHp or selected. setSelected adds/removes selection ring (makeSelectionRing(radius 0.4)) and toggles bar. takeDamage: amount * ctx.effectiveArmorMult(faction) when faction player; clamps, sets dead at <= 0; spark fxBurst. get pos() returns group.position. Helpers: dist2D(p: THREE.Vector3), faceToward(p). ### src/entities/resourceNode.ts export class ResourceNode extends Entity implements IResourceNode. constructor(ctx: IGameCtx, nodeKind: NodeKind, x: number, z: number). Mesh from props factories (variant = id). radius: tree/pine 0.8, rock 1.6, goldmine 2.2, irondeposit 1.8, berrybush 1.2, carcass 1.0. remaining = NODES[kind].amount (caller may override for carcass). harvest(amount: number): number — returns min(remaining, amount), decrements, dead when 0. update: carcass decays CARCASS_DECAY*dt. Not attackable (takeDamage no-op), selectable true (info). hp/maxHp mirror remaining/initial for the panel. ### src/entities/building.ts export class Building extends Entity implements IBuilding. constructor(ctx: IGameCtx, kind: BuildingKind, cx: number, cz: number, opts?: { built?: boolean }). Position at footprint-center formula, y = terrain height (use height at center). Visual: built ? full mesh : constructionSite building mesh with scale.y = 0.08 0.92*buildProgress. Construction: each frame count player villagers in state 'building' whose buildTarget is this and within range -> progress = (count ? Math.sqrt(count) : 0) * dt / def.buildTime; at 1: built=true, remove scaffold, restore scale, hp=maxHp, emit buildingComplete bus message (name " completed"), sound build. Repair: same builders on a BUILT damaged building heal hp at maxHp / (buildTime*2) per builder-sqrt rate. Farm: cropAnchor children swapped to makeCropField(stage, 4.2) when stage changes; growth: if workerId set -> validate via ctx.unitById (alive, state farming/toFarm targeting this) else clear workerId; while a live farmer is adjacent in state farming: cropProgress = dt; cropStage = min(3, floor(cropProgress / (FARMING.growTime/3))). Reset progress/stage to 0 after a harvest is taken (farmer FSM calls a public takeHarvest(): boolean — true if stage 3, resets to 0). Training: if built && trainQueue.length: head.remaining -= dt, at 0 spawn new Unit at pathfinder.nearestFreeAround(rally ?? front-of-building), emit unitTrained, sound train (import Unit from ./unit). addToQueue: queue cap 5, requires state.pop UNITS[kind].pop <= popCap AND payCost, push {kind, remaining: trainTime, total: trainTime}. Tower: if def.attack && built: attackTimer -= dt, find ctx.findNearestEnemyOf('player', pos, range), spawnProjectile from pos (0, 6.2, 0), damage = ctx.effectiveDamage(def.attack.damage, 'player'), reset cooldown. Well: heal player units within radius by rate*dt (cap at maxHp). Townhall/walls: nothing special beyond above. Death: handled by game removal pass. ### src/entities/unit.ts export class Unit extends Entity implements IUnit. constructor(ctx: IGameCtx, kind: UnitKind, x: number, z: number). def = UNITS[kind]; radius 0.55 (knight 0.8). rig = makeHumanoid(kind); setTool(def.tool). Movement: path: THREE.Vector3[] from ctx.pathfinder; advance at def.speed, pop waypoint < 0.35, y = terrain.getHeight, face heading, rig.setWalkPhase(accumulated distance * 2.2); path end -> arrival logic per state. Orders (each clears previous, computes path; unreachable -> stay idle): orderMove -> moving; orderGather(node) -> toNode (walk to pathfinder.nearestFreeAround(node.pos)); orderBuild(b) -> toBuild; orderAttack(t) -> toAttack; orderFarm(farm) -> toFarm (also farm.workerId = this.id). FSM: toNode: in gather range -> gathering (face node, tool: wood axe, stone/gold/iron pick, food-from-bush/carcass axe; swing loop via setAttackPhase; sound chop/mine throttled): carry.amount = NODES[node.nodeKind].gatherRate * ctx.gatherRateMult() * dt via node.harvest; full at GATHER.carryCapacity ctx.carryBonus() OR node dead -> returning: walk to ctx.findDropOff(pos, type) (none -> idle); arrive -> ctx.addResource(type, amount, true), sound harvest, carry = null -> back toNode (node dead -> nearest same-nodeKind node within 24, else idle). toBuild/building: in range -> building w/ hammer swings (Building counts builders); building.built && hp full -> idle. toFarm/farming: stand near cropAnchor w/ scythe; farm.cropStage 3 -> 3s harvest timer -> farm.takeHarvest() -> carry {wheat, FARMING.wheatYield} -> returning to wheat dropOff -> toFarm again. Lost farm (destroyed/reassigned) -> idle. toAttack/attacking: chase target (repath if target moved > 3 from path end, throttle 0.8s), in range (def.range target.radius) -> swing on attackCooldown: melee target.takeDamage(ctx, ctx.effectiveDamage(def.damage, 'player'), this); archer: ctx.spawnProjectile(pos (0,1.4,0), target, dmg, this), sound arrow. Target dead -> villager: nearest carcass node within 8 -> orderGather, else idle; military: re-acquire ctx.findNearestEnemyOf('player', pos, aggroRange) else idle. idle: military scan every 0.5s aggro; villager scan every 1s for carcass within 8 (auto-harvest hunts). Villager hit while in a non-combat state -> flee: orderMove toward townhall. Carry visual rig.setCarry. setWalkPhase only while moving, setIdle when stationary. ### src/entities/enemy.ts export class EnemyUnit extends Entity implements IEnemy. constructor(ctx: IGameCtx, kind: EnemyKind, x: number, z: number). faction enemy. rig makeHumanoid(kind); tools: raider club, brute club, shaman staff, warlord sword. Retarget think every 0.4s (stagger by id): target = nearest player unit OR building within aggroRange, else townhall, else nearest player building, else nearest player unit anywhere; path via pathfinder.nearestFreeAround(target.pos); findPath null -> pick nearest player building by straight-line (walls count) and path adjacent to it. Attack in range target.radius on cooldown: melee swing (setAttackPhase) or shaman: ctx.spawnProjectile (range 13). Wolf: targets nearest player unit OR animal within aggroRange (else wanders); when ctx.dayNight.isNight false -> dies quietly (no bounty: set a public diedQuietly flag the game checks). Movement identical to Unit (shared style, but implement locally). All damage to player passes through their takeDamage (armor applied there). ### src/entities/animal.ts export class Animal extends Entity implements IAnimal. constructor(ctx: IGameCtx, kind: AnimalKind, x: number, z: number). faction wild. rig makeAnimal(kind). Wander: every 2-5s pick random walkable point within 12 and steer directly (no A*; if next cell unwalkable pick new target). Deer/sheep: on takeDamage flee 8u directly away from attacker, then graze 2s (deer is catchable because of the pauses). Boar: on damage, attack the attacker (melee ANIMALS.boar.damage, cooldown 1.3s) until it dies or is 25u away. foodYield -> game spawns carcass on death. ### src/systems/pathfinding.ts export class Pathfinder implements IPathfinder. constructor(grid: IGrid, terrain: ITerrain). A* 8-directional (diagonal blocked if either orthogonal neighbor blocked), octile heuristic, iteration cap 20000. Start/goal snapped to nearest walkable cell (spiral search). Smooth result by line-of-sight waypoint skipping (grid walk between cell centers). Returns world-space Vector3 waypoints with terrain heights, or null. nearestFreeAround(target, radius=6 cells): spiral outward, first walkable cell center as Vector3 (null if none). ### src/systems/combat.ts export class CombatSystem. constructor(scene: THREE.Scene). spawn(from: THREE.Vector3, target: IEntity, damage: number, attacker: IEntity, ctx: IGameCtx): void — arrow mesh (makeArrow), flight time dist/22, lerp from->target current pos with parabolic arc (peak ~dist*0.15), orient along velocity; on arrival: target alive -> target.takeDamage(ctx, damage, attacker); recycle. update(ctx, dt) advances all projectiles. (ctx.spawnProjectile delegates here.) ### src/systems/waves.ts export class WaveSystem. constructor(). update(ctx, dt). Schedule from WAVES (then endlessWave(n) forever after). Nightfall moment = day fraction (1 - TIME.nightFraction). secondsUntil next wave = ((waveDay - day) * 1 (nightStart - time)) * TIME.dayLength (only when positive). Emit waveIncoming ONCE per wave at <= WAVE_WARNING_SECONDS remaining ( horn sound bus message warning). At nightfall of the wave day: spawn composition split across spec.sides distinct random map edges — spawn points = walkable cells within 3 cells of the border, clustered per side; create EnemyUnit per entry (import EnemyUnit from ../entities/enemy), track their ids; emit waveStarted message. While active: all dead -> ctx.state.wave = n, emit waveEnded success message. Also owns night wolves: on nightFell with day >= WOLVES.firstDay, chance WOLVES.nightlyChance -> pack of packMin..packMax wolves at one random edge (not tracked as wave). And wildlife respawn: on dayChanged spawn WILDLIFE_RESPAWN.deerPerDay deer at random edges (import Animal). getNextWaveInfo(ctx): { wave: number; secondsUntil: number } | null. ...

1
292
Acá va el código de R library(shiny) library(bslib) library(dplyr) library(readr) library(sf) library(spdep) library(leaflet) library(DT) library(stringr) library(tibble) # Exploratory spatial autocorrelation for Delitos 2025. # This does not create property-level features. It aggregates incidents to a # hex grid and checks whether counts cluster spatially. BASE_DIR <- "C:/Users/sixto/Documents/CCA_Plusvalia" OUT_DIR <- "C:/Users/sixto/Documents/Codex/2026-06-14/files-mentioned-by-the-user-library/outputs/work/delitos_2025" dir.create(OUT_DIR, recursive = TRUE, showWarnings = FALSE) DELITOS_URL <- "data.buenosaires.gob.ar/data…" DELITOS_LOCAL <- "C:/Users/sixto/Documents/Codex/2026-06-14/files-mentioned-by-the-user-library/outputs/work/spatial_raw/delitos_2025.csv" DELITOS_CACHE <- if (file.exists(DELITOS_LOCAL)) DELITOS_LOCAL else file.path(OUT_DIR, "delitos_2025_raw.csv") BARRIOS_POPULARES_URL <- "data.buenosaires.gob.ar/data…" BARRIOS_POPULARES_LOCAL <- "C:/Users/sixto/Documents/Codex/2026-06-14/files-mentioned-by-the-user-library/outputs/work/spatial_raw/barrios_populares.csv" BARRIOS_POPULARES_CACHE <- if (file.exists(BARRIOS_POPULARES_LOCAL)) { BARRIOS_POPULARES_LOCAL } else { file.path(OUT_DIR, "barrios_populares.csv") } CABA_STREETS_SHP <- file.path(BASE_DIR, "callejero/calles.shp") WORK_CRS <- 3857 norm_txt <- function(x) { x <- toupper(as.character(x)) x <- iconv(x, from = "", to = "ASCII//TRANSLIT") x[is.na(x)] <- "" trimws(x) } scaled_coord <- function(x, axis = c("lon", "lat")) { axis <- match.arg(axis) x_chr <- gsub(",", ".", as.character(x), fixed = TRUE) x_chr <- vapply(x_chr, function(v) { if (is.na(v) || !grepl("^-?\\d \\.\\d \\.", v)) return(v) sign <- if (startsWith(v, "-")) "-" else "" parts <- strsplit(sub("^-", "", v), "\\.")[[1]] paste0(sign, parts[1], ".", paste(parts[-1], collapse = "")) }, character(1)) x <- suppressWarnings(as.numeric(x_chr)) if (all(is.na(x))) return(x) limit <- if (axis == "lon") 180 else 90 for (div in c(10, 100, 1000, 10000, 100000, 1000000, 10000000)) { x <- ifelse(!is.na(x) & abs(x) > limit & abs(x / div) <= limit, x / div, x) } x } read_delitos <- function(force = FALSE) { cache_path <- DELITOS_CACHE if (force || !file.exists(cache_path)) { cache_path <- file.path(OUT_DIR, "delitos_2025_raw.csv") download.file(DELITOS_URL, cache_path, mode = "wb", quiet = TRUE) } header <- readLines(cache_path, n = 1, warn = FALSE, encoding = "UTF-8") delim <- if (str_count(header, ";") > str_count(header, ",")) ";" else "," raw <- read_delim( cache_path, delim = delim, show_col_types = FALSE, col_types = cols(.default = col_character()), locale = locale(encoding = "UTF-8") ) names(raw) <- tolower(gsub("-", "_", names(raw))) raw |> mutate( tipo_norm = norm_txt(tipo), subtipo_norm = norm_txt(subtipo), uso_arma_norm = norm_txt(uso_arma), uso_moto_norm = norm_txt(uso_moto), barrio_norm = norm_txt(barrio), lon = scaled_coord(longitud, axis = "lon"), lat = scaled_coord(latitud, axis = "lat"), cantidad_num = suppressWarnings(as.numeric(cantidad)), cantidad_num = ifelse(is.na(cantidad_num), 1, cantidad_num), grupo = case_when( str_detect(tipo_norm, "HOMICIDIO") ~ "Homicidios", str_detect(tipo_norm, "^ROBO") ~ "Robos", str_detect(tipo_norm, "^HURTO") ~ "Hurtos", TRUE ~ "Otros" ) ) |> filter( !is.na(lon), !is.na(lat), between(lon, -59, -58), between(lat, -35, -34) ) |> st_as_sf(coords = c("lon", "lat"), crs = 4326, remove = FALSE) |> st_transform(WORK_CRS) } read_barrios_populares <- function(force = FALSE) { cache_path <- BARRIOS_POPULARES_CACHE if (force || !file.exists(cache_path)) { cache_path <- file.path(OUT_DIR, "barrios_populares.csv") download.file(BARRIOS_POPULARES_URL, cache_path, mode = "wb", quiet = TRUE) } bp <- read_delim( cache_path, delim = ",", show_col_types = FALSE, col_types = cols(.default = col_character()), locale = locale(encoding = "UTF-8") ) names(bp) <- tolower(names(bp)) if (!"geometry" %in% names(bp)) return(NULL) st_as_sf(bp, wkt = "geometry", crs = 4326) |> st_make_valid() |> st_transform(WORK_CRS) } get_caba_boundary <- function() { st_read(CABA_STREETS_SHP, quiet = TRUE) |> st_transform(WORK_CRS) |> st_geometry() |> st_buffer(180) |> st_union() |> st_as_sf() |> st_make_valid() } make_hex_counts <- function(delitos, boundary, selected_groups, hex_size) { d <- delitos |> filter(.data$grupo %in% selected_groups) hex <- st_make_grid(boundary, cellsize = hex_size, square = FALSE) |> st_as_sf() |> mutate(hex_id = row_number()) |> st_filter(boundary, .predicate = st_intersects) |> st_make_valid() if (nrow(d) == 0) { hex$count <- 0 return(hex) } joined <- st_join(d, hex, join = st_within) counts <- joined |> st_drop_geometry() |> filter(!is.na(hex_id)) |> group_by(hex_id) |> summarise(count = sum(cantidad_num, na.rm = TRUE), .groups = "drop") hex |> left_join(counts, by = "hex_id") |> mutate(count = ifelse(is.na(count), 0, count)) } run_moran <- function(hex_counts) { nb <- poly2nb(hex_counts, queen = TRUE) lw <- nb2listw(nb, style = "W", zero.policy = TRUE) x <- hex_counts$count global <- moran.test(x, lw, zero.policy = TRUE) local <- localmoran(x, lw, zero.policy = TRUE) x_mean <- mean(x, na.rm = TRUE) lag_x <- lag.listw(lw, x, zero.policy = TRUE) lag_mean <- mean(lag_x, na.rm = TRUE) hex_counts |> mutate( lag_count = lag_x, local_i = local[, "Ii"], local_p = local[, "Pr(z != E(Ii))"], lisa_cluster = case_when( local_p > 0.05 ~ "No significativo", count >= x_mean & lag_count >= lag_mean ~ "High-High", count <= x_mean & lag_count <= lag_mean ~ "Low-Low", count >= x_mean & lag_count <= lag_mean ~ "High-Low", count <= x_mean & lag_count >= lag_mean ~ "Low-High", TRUE ~ "No significativo" ), moran_i = unname(global$estimate[["Moran I statistic"]]), moran_p = global$p.value, expected_i = unname(global$estimate[["Expectation"]]) ) } delitos_all <- read_delitos(force = FALSE) barrios_populares <- read_barrios_populares(force = FALSE) caba_boundary <- get_caba_boundary() ui <- page_sidebar( title = "Autocorrelacion espacial - Delitos 2025", theme = bs_theme(version = 5, bootswatch = "litera"), sidebar = sidebar( width = 330, checkboxGroupInput( "grupo", "Grupo", choices = c("Homicidios", "Robos", "Hurtos", "Otros"), selected = "Robos" ), selectInput( "hex_size", "Tamano hexagono", choices = c("500 m" = 500, "750 m" = 750, "1000 m" = 1000, "1500 m" = 1500), selected = 750 ), checkboxInput("show_bp", "Mostrar barrios populares", value = TRUE), actionButton("run", "Actualizar Moran / LISA"), hr(), tags$p( class = "small text-muted", "Moran se calcula sobre conteos agregados por hexagono. Para homicidios conviene usar hexagonos mas grandes porque son pocos eventos." ) ), navset_tab( nav_panel("LISA mapa", br(), leafletOutput("lisa_map", height = 720)), nav_panel("Moran global", br(), verbatimTextOutput("global_moran")), nav_panel("Tabla hex", br(), DTOutput("hex_table")) ) ) server <- function(input, output, session) { moran_layer <- eventReactive(input$run, { hex_counts <- make_hex_counts( delitos = delitos_all, boundary = caba_boundary, selected_groups = input$grupo, hex_size = as.numeric(input$hex_size) ) run_moran(hex_counts) }, ignoreInit = FALSE) output$lisa_map <- renderLeaflet({ x <- moran_layer() validate(need(nrow(x) > 0, "Sin hexagonos.")) x4326 <- st_transform(x, 4326) bp4326 <- if (inherits(barrios_populares, "sf")) st_transform(barrios_populares, 4326) else NULL pal_lisa <- colorFactor( palette = c( "High-High" = "#d00000", "Low-Low" = "#1d4ed8", "High-Low" = "#f97316", "Low-High" = "#22c55e", "No significativo" = "#d1d5db" ), domain = c("High-High", "Low-Low", "High-Low", "Low-High", "No significativo") ) m <- leaflet(x4326, options = leafletOptions(preferCanvas = TRUE)) |> addProviderTiles(providers$CartoDB.Positron) |> addPolygons( fillColor = ~pal_lisa(lisa_cluster), fillOpacity = ~ifelse(lisa_cluster == "No significativo", 0.18, 0.62), color = "#ffffff", weight = 0.4, popup = ~paste0( "<b>Cluster:</b> ", lisa_cluster, "<br>", "<b>Count:</b> ", count, "<br>", "<b>Lag count:</b> ", round(lag_count, 2), "<br>", "<b>Local I:</b> ", round(local_i, 4), "<br>", "<b>p:</b> ", signif(local_p, 3) ) ) |> addLegend(position = "bottomright", pal = pal_lisa, values = ~lisa_cluster, title = "LISA") if (isTRUE(input$show_bp) && inherits(bp4326, "sf") && nrow(bp4326) > 0) { m <- m |> addPolygons( data = bp4326, fillColor = "#7b2cbf", fillOpacity = 0.08, color = "#5a189a", weight = 1.1, label = ~paste0(nombre, " | ", tipo) ) } m }) output$global_moran <- renderPrint({ x <- moran_layer() cat("Grupo:", paste(input$grupo, collapse = ", "), "\n") cat("Hex size:", input$hex_size, "m\n") cat("Hexagonos:", nrow(x), "\n") cat("Eventos agregados:", sum(x$count, na.rm = TRUE), "\n\n") cat("Global Moran's I:", round(unique(x$moran_i)[1], 5), "\n") cat("Expected I:", round(unique(x$expected_i)[1], 5), "\n") cat("p-value:", signif(unique(x$moran_p)[1], 5), "\n\n") cat("Interpretacion rapida:\n") if (unique(x$moran_p)[1] <= 0.05 && unique(x$moran_i)[1] > 0) { cat("- Hay autocorrelacion espacial positiva: los conteos se agrupan.\n") } else if (unique(x$moran_p)[1] <= 0.05 && unique(x$moran_i)[1] < 0) { cat("- Hay autocorrelacion negativa: patron tipo dispersion/alternancia.\n") } else { cat("- No hay evidencia fuerte de autocorrelacion global con este grid/filtro.\n") } }) output$hex_table <- renderDT({ x <- moran_layer() |> st_drop_geometry() |> arrange(local_p) datatable( x |> select(hex_id, count, lag_count, local_i, local_p, lisa_cluster, moran_i, moran_p), rownames = FALSE, options = list(pageLength = 25, scrollX = TRUE) ) }) } shinyApp(ui, server)

1
1
56
インスタ用の囲碁のリール動画の自動作成システムつくりました。 棋譜ファイルを用意して、以下の雑なプロンプトで動画ができるやつ。 === public/shicho.sgfを使ってシチョウのデモンストレーション動画を作る。初期画面で 「△の白石を追いかけて取ります。」1手ずつ進めていって最後で「全部まとめて取りました。囲碁の石取りの必殺技シチョウです」で締める。途中、いろいろな視覚効果や効果音を交えて派手に。 === AI氏はファイルを調べて === 確認できました。最後の13手目 B[aa] で白7子を一気に取るシチョウです。取られる白石7子の位置も特定しました。 座標計算(cellSize=(boardSize-8)/7、中心 margin index*cellSize)に基づいて、△マーカー・アタリ演出・大爆発を正確に石の位置へ重ねます。9:16縦型(1080×1920)で作成します。 ではコンポーネントを書きます。 === って感じで仕事してくれる。
1
1
4
2,144
14 Sep 2025
smartest coder in the universe (THE CELLSIZE IN THE ELSE PART SHOULD BE DIFFERENT IDK WHY IT WAS THE EXACT SAME)
2
61
Reshaping during healing in plants :An Insightful article by Sh D. Balasubramanian #CellGeometry #CellSize #Geometry #Plants #Healing #Cells #stressed #Adaptation #Morphogenesis #stemcells #Regeneration #GeneticPathways #Science #Research #UPSC Source: TH
2
8
504
🦋🦋🦋 Artemis @threejs Steal my post processing. <EffectComposer> <ASCII invert cellSize={1} /> </EffectComposer> import { ASCII, EffectComposer } from '@react-three/postprocessing';
3
4
50
5,569
来一个新出的 Gemini-2.5-Pro-Preview-05-06 的画迷宫 demo,prompt 如下,大家可以试试 : 请使用 p5.js 库实现一个迷宫生成和寻路的可视化程序。 程序应包含以下几个主要功能: 1. **初始化 (`setup` 函数)**: * 设置画布大小和迷宫网格的尺寸 (行数 `rows`, 列数 `cols`) 以及单元格大小 `cellSize`。 * 创建一个二维数组 `grid` 来表示迷宫,初始时所有单元格都标记为墙。 * 选择一个起始单元格,将其标记为路径。 * 调用迷宫生成函数来创建迷宫结构。 * 多次调用一个函数来修剪迷宫中的死路 (dead ends)。 * 调用一个函数来标记迷宫中被墙完全包围的区域 (holes)。 * 调用寻路函数找到从指定起点到指定终点的路径。 * 存储寻路结果以供绘制。 2. **绘制 (`draw` 函数)**: * 设置背景色。 * 遍历 `grid` 数组。 * 根据单元格的状态绘制矩形:墙使用一种颜色,路径使用另一种颜色。 * 将被寻路函数标记为访问过的路径单元格用特殊颜色高亮显示。 * 将被标记为 "holes" 的墙单元格用另一种特殊颜色显示。 * 明确标记出迷宫的起点和终点 (例如,使用不同的颜色)。 * 绘制完成后停止循环 (`noLoop`)。 3. **迷宫生成 (`generateMaze` 函数)**: * 使用基于堆栈的深度优先搜索 (或其他类似算法,如随机 Prim) 来生成迷宫。 * 维护一个 `stack` 来追踪当前的路径。 * 从当前单元格开始,查找未访问的邻居(通常是间隔一个单元格的邻居)。 * 如果找到邻居: * 随机选择一个邻居(可以使用带权重的随机选择函数)。 * 打通当前单元格和选中邻居之间的墙。 * 将选中邻居标记为路径并压入堆栈,设为当前单元格。 * 如果没有未访问的邻居,则从堆栈中回溯。 * 重复此过程直到堆栈为空。 4. **查找未访问的邻居 (`getUnvisitedNeighbors` 函数)**: * 给定一个单元格坐标,检查其上、下、左、右方向(间隔一个单元格)的邻居。 * 返回那些在边界内且尚未被访问过(仍是墙)的邻居坐标列表。 5. **带权重的随机方向选择 (`weightedRandomDirection` 函数)**: * 接受一个邻居列表和对应的方向权重。 * 根据权重随机选择一个邻居返回。 6. **死路修剪 (`cull_dead_ends` 函数)**: * 随机选择一个路径单元格。 * 检查它是否是一个死路(只有一个路径邻居,且不是起点或终点)。 * 如果是死路,则沿着该死路回溯若干步,直到遇到岔路口或达到步数限制。 * 将这条死路路径填充为墙。 * 此函数可以被多次调用以简化迷宫。 7. **标记空洞 (`mark_holes` 函数)**: * 遍历迷宫中的墙单元格。 * 检查每个墙单元格周围的 8 个邻居。 * 如果一个墙单元格被 8 个(或接近 8 个)非路径单元格包围,则将其标记为一个特殊的 "hole" 值(例如 7)。 8. **深度优先寻路 (`find_path_dfs` 函数)**: * 使用深度优先搜索算法在生成的迷宫 `grid` 中查找从 `startp` 到 `endp` 的路径。 * 维护一个 `visited` 数组来记录访问过的单元格。 * 使用一个栈 `st` 来进行搜索。 * 在选择下一个要访问的邻居时,可以使用一个辅助函数 (`sort_to_p`) 根据邻居到终点的距离进行排序(例如优先选择离终点更远的,以模拟某种探索策略)。 * 返回 `visited` 数组(标记了路径上的点)、搜索步数和遇到的分支数。 9. **辅助函数**: * `set_in`: 检查一个点是否存在于一个点集中。 * `sort_to_p`: 根据点到目标点的距离对点列表进行排序。 请确保: - 所有代码都包含在一个 HTML 文件中。
4
4
63
8,190
What molecular mechanisms determine cell size dependence of proteins? Read "Eukaryotic cell size regulation and its implications for cellular function and dysfunction" by Chadha et al to find out: ow.ly/NJx450Ulk0r #OpenAccess #CellSize
1
3
401
Congratulations to my lab neighbour! 🥳 So well deserved! This is the lab you want to join if you are interested in #cellsize #mitochondria #modelorganisms and are looking for a fantastic environment! 👇
Congratulations: Dr. Kurt Schmoller Receives #ERC Consolidator Grant! 👏 👉t1p.de/pty6f 💡The project, #MITOSIZE, aims to unravel how cells regulate mitochondrial DNA levels – an essential process for maintaining cell health and preventing disease. 🧬Using yeast and algae as model organisms, the @SchmollerLab will investigate how mitochondrial DNA adapts to cell size and environmental changes, with potential insights into #aging and disease. 🎉 This achievement marks the 61st ERC grant for #HelmholtzMunich! @epigeneticsHMGU @ERC_Research #MitochondrialResearch #prevention #EU #ERCCoG #ScienceInnovation #epigenetics #CellCycle
6
338
🔬Researchers Chadha, Khurana & Schmoller from @HelmholtzMunich explore the link between #CellSize & cell function in this innovative review. Discover more: ow.ly/NtzK50TN2mL
2
5
339
🚨Preprint Alert! 👏Congratulations to the fantastic 1st author @YagyaChadha, as well as @frank_pado & Igor for the great job. @SchmollerLab, together with @robert_ife lab, uncovered new insights into #cellsize adaptation during nutrient shifts in yeast. @HelmholtzMunich rocks
Single-cell imaging reveals a key role of Bck2 in budding yeast cell size adaptation to nutrient challenges biorxiv.org/cgi/content/shor… #biorxiv_cellbio
4
12
962
Cells maintain narrow #cellsize distributions, but also adapt size in changing conditions. We found that regulators with redundant roles in steady state have specific functions in size adaptation upon a nutrient shift. biorxiv.org/cgi/content/shor… @YagyaChadha @frank_pado @robert_ife

1
13
69
7,266
🆕Review from @HelmholtzMunich highlights the importance of #CellSize Fig. 5: Cell size acts as a regulator of embryonic development and differentiation. Find out more: ow.ly/SySB50Tpxzf
2
323
Thrilled to share our in-depth review on #cellsize! 📏🔬Explore how size affects cell function and its links to pathophysiological conditions.
#Cellsize is important for many cellular processes, including biosynthesis, organelle homeostasis and development. If you need an overview of how cell size is controlled, and how it affects cell function, we have you covered: doi.org/10.1152/physrev.0004… @YagyaChadha @arohikhurana1
1
1
5
354
🗣️New Review article from one of our #Epigenetics research groups. Super congrats @SchmollerLab, @arohikhurana1 and @YagyaChadha 👏 If you want to know the basis and the last news about eukaryotic #cellsize research, read this awesome review: journals.physiology.org/doi/…
#Cellsize is important for many cellular processes, including biosynthesis, organelle homeostasis and development. If you need an overview of how cell size is controlled, and how it affects cell function, we have you covered: doi.org/10.1152/physrev.0004… @YagyaChadha @arohikhurana1
3
11
737